C # Thread.Sleep waking up immediately

I am using the code below

Thread.Sleep(5); 

at the end of the while loop. To try to get a 5 ms delay between iterations.

Sometimes he sleeps for 16 ms. I understand and accept this, because it depends on when the CPU wraps around the thread service. However, as soon as he woke up the next iteration, he seemed to wake up right after sleep (I register with timestamps). Is there a problem with using such a short wait interval that it is treated as zero?

+6
multithreading c #
source share
4 answers

Your problem is that on most modern machines DateTime.UtcNow has a resolution of about 10-15 ms (although I see the documentation says about it about 10 ms with NT 3.5). If you want a higher resolution, see the Stopwatch class, in particular Stopwatch.GetTimestamp () .

Also note that the stopwatch will only use high resolution timers, if available ( Stopwatch.IsHighResolution will tell you at run time). If not, it returns to DateTime.UtcNow.Ticks.

+21
source share

Most likely the problem is that your timer has a limited resolution. If it is updated, say, every 10 ms, you will see the same time stamp at some iterations, even if 5 m has passed.

What timer do you use to create timestamps?

+4
source share

If I remember correctly the NT-slice, which was introduced in the NT kernel and was still active in the same way as XP, it works at about 5 ms. We built the application in real time and ran into this problem. You will not be able to consistently receive a sleep time of 5 ms. We found that you sometimes get 10-16 ms, sometimes not ms, and sometimes rarely get 5 ms.

I did these tests about 5 years ago, although everything has changed since then.

+1
source share

What system are you using? Small intervals may depend on the processor and how high resolution it supports. I ran the application on a handheld computer when the resolution of the timer itself was 16 ms. So it may be related to equipment. Try increasing the time period to say 30 ms and see if it will work then.

0
source share

All Articles