Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Problems with using Thread.Sleep for short times

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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++)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...