I have a block of code that will be called relatively often. Prior to it being called I need a 2000ms delay to take place.
The first thing that has come to mind is creating/disposing of a timer every time the method is called.
To accomplish this I’m using a Timer (see code). My question is…any dangers/problems calling Dispose inside of the anonymous method below? Recommendations of a better approach?
Are there any downsides to doing the following? Bad idea?
delayTimer = new Timer() { Interval = 2000 };
{
delayTimer.Tick += (sender2, e2) =>
{
((Timer)sender2).Stop();
MessageBox.Show("Do something after 2000ms");
delayTimer.Dispose();
};
}
One thing you can do differently is move the Dispose for the timer to the front of the anonymous method. This way, even if you throw an exception later in the method, you’ve still Disposed the timer. I’ve used this kind of pattern before and it’s a reasonably clean way to get a delayed callback.
If you’re using C#5, there is a very nice Task.Delay method you can await to get a timer callback within an async method. This is often used to implement timeouts in combination with a call to WaitAny like this: