refer to : http://stackoverflow.com/questions/91108/how-do-i-get-my-c-sharp-program-to-sleep-for-50-msec
here are basically 3 choices for waiting in (almost) any programming language:
- Loose waiting
- Executing thread blocks for given time (= does not consume processing power)
- No processing is possible on blocked/waiting thread
- Not so precise
- Tight waiting (also called tight loop)
- processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time)
- Some actions can be performed while waiting
- Very precise
- Combination of previous 2
- It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.
for 1. - Loose waiting in C#:
Thread.Sleep(numberOfMilliseconds);
However, windows thread scheduler causes acccuracy of Sleep()
to be around 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).
for 2. - Tight waiting in C# is:
Stopwatch stopwatch = Stopwatch.StartNew(); while (true) { //some other processing to do possible if (stopwatch.ElapsedMilliseconds >= millisecondsToWait) { break; } }
We could also use DateTime.Now
or other means of time measurement, but Stopwatch
is much faster (and this would really become visible in tight loop).
for 3. - Combination:
Stopwatch stopwatch = Stopwatch.StartNew(); while (true) { //some other processing to do STILL POSSIBLE if (stopwatch.ElapsedMilliseconds >= millisecondsToWait) { break; } Thread.Sleep(1); //so processor can rest for a while }
This code regularly blocks thread for 1ms (or slightly more, depending on OS thread scheduling), so processor is not busy for that time of blocking and code does not consume 100% of processor's power. Other processing can still be performed in-between blocking (such as: updating of UI, handling of events or doing interaction/communication stuff).