Is there a QTimer::singleShot equivalent in C# Windows Forms? - c#

Is there an analog to the following static function from the Qt library in Windows Forms?
http://doc.qt.io/qt-5/qtimer.html#singleShot
The best I can come up with is the following:
ThreadPool.QueueUserWorkItem((o) =>
{
Thread.Sleep(someNumberOfMilliseconds);
DoDelayedWorkHere();
});
UPDATE
This does the trick using System.Windows.Forms.Timer.
var timer = new System.Windows.Forms.Timer();
timer.Interval = someNumberOfMilliseconds;
timer.Tick += (o, args) =>
{
timer.Stop();
DoDelayedWorkHere();
};
timer.Start();

QTimer is a synchronous timer, just like the Winforms Timer. Threading or one of the other Timer classes is not a substitute. A single-shot is easy to implement, just set the timer's Enabled property to false in the Tick event handler. No danger of a race:
private void timer1_Tick(object sender, EventArgs e) {
((Timer)sender).Enabled = false;
// etc..
}

How about System.Threading.Timer? Use one of the constructors with the period parameter and specify the parameter accordingly.

Related

C# - Problem with System.Timer Tick Eventhandling

I've got a problem while programming a little game for myself.
I'm using the "System.Timers"-Timer and want to decrease the value of a progress bar
by every tick of the timer. There I faced my problem. I can't set a custom event handler to decrease the value of the progress bar.
I've using for the Timer the following code:
private Timer t = new Timer();
t.Interval = 600000;
t.Elapsed += Ended; //For ending event
t.AutoReset = true;
So how can I register a tick to decrease the value of the progress bar.
Thank you for your answers in advance.
Greetings
SirCodiac
You cant invoke a control from system.timers. In order to invoke the progress bar either use System.Windows.Forms.Timer or use a MethodInvoker as below:
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new MethodInvoker(delegate { progressBar1.Value++; }));
}
else
{
progressBar1.Value++;
}
}

WCF+ timer. A bad practice?

I would like for my service to be able to initiate communication with other services.
In order for it to act like a client and start the communication, I thought that an initialized in the constructor timer that calls a method every x seconds could be a good idea.
Is it a bad idea?
I can't see what could be wrong with this approach.
You could utilize System.Timers.Timer - https://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx
Set its Interval to value at which you want to raise Elapsed event of timer. Subscribe to Elapsed event using an event handler which you implement, in which you would communicate with the external service.
Edit: simple example
class Program
{
private static void timer_ElapsedEventHandler(object sender, EventArgs e)
{
// communicate to external service
Console.WriteLine("ElapsedEventHandler fired");
}
static void Main(string[] args)
{
var timer = new System.Timers.Timer();
timer.Interval = 3000;
timer.Elapsed += timer_ElapsedEventHandler;
timer.Start();
Console.WriteLine("Timer started");
Console.ReadLine();
}
}

How to use a timer to wait?

I am trying to delay events in my method by using a timer, however i do not necessarily understand how to use a timer to wait.
I set up my timer to be 2 seconds, but when i run this code the last call runs without a 2 second delay.
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
timer.Interval = (1000) * (2); // Timer will tick evert second
timer.Enabled = true; // Enable the timer
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
label1.Text = "second";
}
So when i click my button, it immediately shows label1 as "second", as opposed to changing to "first", waiting 2 seconds, then changing to "second". I have read lots of threads here about using timers instead of thread.sleep, but i cannot seem to find/figure out how to actually implement that.
If you're using C# 5.0 await makes this much easier:
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
await Task.Delay(2000);
label1.Text = "second";
}
timer.Start() just starts the timer but immediately returns while the timer is running in the background. So between setting the label text to first and to second there is nearly no pause. What you want to do is wait for the timer to tick and only then update the label again:
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
label1.Text = "second";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
}
Btw. you should not set timer.Enabled to true, you are already starting the timer using timer.Start().
As mentioned in the comments, you could put the timer creation into a method, like this (note: this is untested):
public void Delayed(int delay, Action action)
{
Timer timer = new Timer();
timer.Interval = delay;
timer.Tick += (s, e) => {
action();
timer.Stop();
};
timer.Start();
}
And then you could just use it like this:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
Delayed(2000, () => label1.Text = "second");
}
Tergiver’s follow-up
Does using Delayed contain a memory leak (reference leak)?
Subscribing to an event always creates a two-way reference.
In this case timer.Tick gets a reference to an anonymous function (lambda). That function lifts a local variable timer, though it's a reference, not a value, and contains a reference to the passed in Action delegate. That delegate is going to contain a reference to label1, an instance member of the Form. So is there a circular reference from the Timer to the Form?
I don't know the answer, I'm finding it a bit difficult to reason about. Because I don't know, I would remove the use of the lambda in Delayed, making it a proper method and having it, in addition to stopping the timer (which is the sender parameter of the method), also remove the event.
Usually lambdas do not cause problems for the garbage collection. In this case, the timer instance only exists locally and the reference in the lambda does not prevent the garbage collection to collect the instances (see also this question).
I actually tested this again using the .NET Memory Profiler. The timer objects were collected just fine, and no leaking happened. The profiler did give me a warning that there are instances that “[…] have been garbage collected without being properly disposed” though. Removing the event handler in itself (by keeping a reference to it) did not fix that though. Changing the captured timer reference to (Timer)s did not change that either.
What did help—obviously—was to call a timer.Dispose() in the event handler after stopping the timer, but I’d argue if that is actually necessary. I don’t think the profiler warning/note is that critical.
If all you're trying to do is change the text when the timer ticks, would you not be better off putting...
label1.Text = "second";
...In the timer tick, either before or after you change the timer to enabled = false;
Like so;
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
label1.Text = "second";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
timer.Start();
}
private bool Delay(int millisecond)
{
Stopwatch sw = new Stopwatch();
sw.Start();
bool flag = false;
while (!flag)
{
if (sw.ElapsedMilliseconds > millisecond)
{
flag = true;
}
}
sw.Stop();
return true;
}
bool del = Delay(1000);

How to delay Silverlight's loading screen?

I have an experimental project in silverlight, that has no database and scarce resources. Now, I wanted to know if you can prolong or delay the Silverlight loading screen, so I can check what I have modified in the loading page. Problem is, it loads too fast for me to check. I have no data to fetch from the webservice or any resources needed. I'm just experimenting in modifying Silverlight's load page. Can this be done code-wise? Any help would be appreciated. Thanks.
Already found the answer. I just needed a timer for things. thanks for all the queries, anyway
private void Application_Startup(object sender, StartupEventArgs e)
{
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(10);
EventHandler eh = null;
eh = (s, args) =>
{
timer.Stop();
this.RootVisual = new Test();
timer.Tick -= eh;
};
timer.Tick += eh;
timer.Start();
}

How to block a timer while processing the elapsed event?

I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event may interfere with others. I implemented the below solution, but something feels wrong; it seems like either I should be using the timer differently or using another object within the threading space. The timer seemed to fit best because I do need to periodically check for a status, but sometimes checking will take longer than my interval. Is this the best way to approach this?
// member variable
private static readonly object timerLock = new object();
private bool found = false;
// elsewhere
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.Start();
public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
lock(timerLock)
{
if (!found)
{
found = LookForItWhichMightTakeALongTime();
}
}
}
You could set AutoReset to false, then explicitly reset the timer after you are done handling it. Of course, how you handle it really depends on how you expect the timer to operate. Doing it this way would allow your timer to drift away from the actual specified interval (as would stopping and restarting). Your mechanism would allow each interval to fire and be handled but it may result in a backlog of unhandled events that are handled now where near the expiration of the timer that cause the handler to be invoked.
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed += Timer_OnElapsed;
timer.AutoReset = false;
timer.Start();
public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
if (!found)
{
found = LookForItWhichMightTakeALongTime();
}
timer.Start();
}
I usually stop the timer while processing it, enter a try/finally block, and resume the timer when done.
If LookForItWhichMightTakeALongTime() is going to take a long time, I would suggest not using a System.Windows.Forms.Timer because doing so will lock up your UI thread and the user may kill your application thinking that it has frozen.
What you could use is a BackgroundWorker (along with a Timer if so desired).
public class MyForm : Form
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public MyForm()
{
InitializeComponents();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.RunWorkerCompleted +=
backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = LookForItWhichMightTakeALongTime();
}
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
found = e.Result as MyClass;
}
}
And you can call RunWorkerAsync() from anywhere you want to, even from a Timer if you want. And just make sure to check if the BackgroundWorker is running already since calling RunWorkerAsync() when it's running will throw an exception.
private void timer_Tick(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
backgroundWorker.RunWorkerAsync();
}
timer.enabled = false
or
timer.stop();
and
timer.enabled = true
or
timer.start();
I use the System.Threading.Timer like so
class Class1
{
static Timer timer = new Timer(DoSomething,null,TimeSpan.FromMinutes(1),TimeSpan.FromMinutes(1));
private static void DoSomething(object state)
{
timer = null; // stop timer
// do some long stuff here
timer = new Timer(DoSomething, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
}

Categories

Resources