I need to be able to delay the event handlers for some controls (like a button) to be fired for example after 1 sec of the actual event (click event for example) .. is this possible by the .net framework ?
I use a timer and call my code from the timer's tick event as below but I am not sure if this is the best approach !
void onButtonClick( ..)
{
timer1.Enabled = true;
}
void onTimerTick( ..)
{
timer.Enabled = false;
CallMyCodeNow();
}
Perhaps you could make a method that creates the timer?
If you're only doing this for one control, the timer approach will work fine. A more robust approach supporting multiple controls and types of events looks something like this:
Maintain a
Queue<Event>
in your form and have UI events that need to be delayed add them to the queue, e.g.:Make your timer tick 10 times a second or so, and have its Tick event handler look like this:
Before coming to your question, just having read the summary bit from the main questions page, a timer was exactly what I was going to suggest.
This looks pretty clean to me. It means you can easily "cancel" the delayed event if you need to, by disabling the timer again, for example. It also does everything within the UI thread (but without reentrancy), which makes life a bit simpler than other alternatives might be.
You can use:
That will pause the current Thread for one second. So I would do that...
Best Regards!
For those limited to .NET 2.0, here is another take on Bengt's helpful solution:
If you're looking for a more fancy solution, you may want to take a look at my Reactive LINQ project. The link doesn't show how to solve the particular problem you're having, but it should be possible to solve in quite an elegant style using the technique described there (in the whole 4-article series).