Problems with using Thread.Sleep for short times

独自空忆成欢 提交于 2019-11-27 07:55:00

问题


I have an app with 2 threads (now), but it seems that function Thread.Sleep() doesn't work very good. It sleeps threads but it takes much more time (for example- I want to sleep it for 5ms and it sleeps for 0,3s or more). Here is code:

int vlakien = 2;
Thread[] vlakna; 
vlakna = new Thread[vlakien];

for (int i = 0; i < vlakien; i++) 
{ try { vlakna[i] = new Thread(new ThreadStart(utok)); vlakna[i].Start(); } }

private void utok()
{
  //some code
  Thread.Sleep(5);
  //some code
}

Also I tried to sleep it with Stopwatch in the function utok and it also takes more time:

Stopwatch SW = new Stopwatch(); SW.Start();
while(SW.ElapsedMilliseconds < 5000) ;

Please help.


回答1:


15ms is the thread time slice on windows ( you can actually mess with windows and change that.... not at all recommended). Things can give their time slices up early, but anything could take their full time slice.

So its really hard to get any better than that, in fact, realistically 20 or 30 ms is more likely. I used to do real time processing which had a hard real time limit of 50ms. That worked well on windows if you obeyed certain rules ( it was in C++)




回答2:


As others have indicated, the default resolution of Sleep is 10 or 15 milliseconds, depending on the edition of Windows.

However, you can reprogram the timer to use a 1 millisecond resolution by issuing a

timeBeginPeriod(1);
timeEndPeriod(1);

where

[DllImport(WINMM)]
internal static extern uint timeBeginPeriod(uint period);   

We do this in our serial communications services where being able to accurately space out sends in time is important. Some people are reluctant to do this because it causes Windows to do other things that are based off of the timer more frequently as well. In reality this has caused no discernible issues for us, and we have hundreds of installs each with hundreds of serial devices connected.




回答3:


Sleep in Microsoft C# guarantees a minimum amount of time. It sleeping less than 5 milliseconds is definitely a problem. Also Stopwatch may not be very precise measurement, try the high precision media timers.




回答4:


It is affected by resolution of the system clock. It is around 15ms...you cannot go below resolution of the system clock. Take a look at this link (it is C++ but you will get idea about timer resolutions).




回答5:


The parameter passed into Thread.Sleep is a minimum time to sleep, not an exact time.



来源:https://stackoverflow.com/questions/8844766/problems-with-using-thread-sleep-for-short-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!