Monday, October 6, 2008

Make C# Application Wait Amount of Time

Stalling for Time

C#.Net programs sometimes need to wait a certain amount of time before carrying out the rest of the code. For example, an application that reminds users every 15 minutes to do something has to stall for 15 minutes.
While you can do time-measuring algorithms in C# with the Timer class, let's try to use a simpler way...

DateTime vs StopWatch

If you remember the code speed test utility, there are two C# classes (not including Timer) that can measure time, the DateTime class and the System.Diagnostics.StopWatch class.
The DateTime class is good if you want to work with loose amounts of time, meaning that 14.98 seconds would be okay if you were aiming for 15.
The StopWatch class on the other hand is as precise as you can get with only C# code.
Whichever one you use is up to you...

How to Stall for Time

The basic way to stall for time in C# will be to use a while loop. In theory, we just need the loop to run in circles until enough time has passed. The example uses DateTime, but the StopWatch object would work too...
DateTime start = DateTime.Now;

while (DateTime.Now.Subtract(start).Seconds < 15)
{
}
That source code will work, but it is not elegant just yet. The problem is it freezes the C# program until the 15 seconds are over. Even worse, it eats up the CPU attention.
To keep the application responsive, you need to add the following C# line inside the loop:
Application.DoEvents();
That makes the applicaiton process its messages even while the loop is running. Thus normal UI interaction is kept running.
To prevent the CPU from going insane:
System.Threading.Thread.Sleep(1);
Technically that C# code can reduce how accurate the stalling time is, but giving the loop a 1 millisecond break per iteration, frees up the CPU.
Remember, both of those lines go inside the loop. And with that, you now have an elegant way to stall for time with simple C# code.

No comments: