C# Programming > Miscellaneous

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, with a wait loop.

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 decently accurate, most applications would have a decent wait loop using DateTime. However if you want a more accurate waiting loop, the StopWatch class 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 prevents the CPU from going crazy.

Remember, both of those lines go inside the wait loop. And with that, you now have an elegant way to stall for time with simple C# code.

Back to C# Article List