Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason of using Thread.Sleep in multi-threaded applications?

Often times I when I see some multi-threaded code, I see Thread.Sleep() statements in the code.

I even had a crash where I was trying to figure out the problem, so commented out most of the multi-threaded code and slowly brought it and for the final piece when I added a for statement like:

for ( int i = 0; i < 1000000; ++i )
    ++i;

it didn't crash. So now I replaced it Thread.Sleep() and it seems to work. I can't repro it easily to post it here, but is using Thread.Sleep() necessary for multi-threaded applications?

What's the purpose of them? Would it lead to unexpected results if not used?

EDIT: Btw I am using the BackgroundWorker and only implementing my stuff in there, but not sure what causes this. Although I am using an API which is the hosting app where the app is not multi threaded. So for instance I think I can't call it's API functions on several threads at once. Not sure, but that was my guess.

like image 567
Joan Venge Avatar asked Dec 13 '22 14:12

Joan Venge


1 Answers

Typically, Thread.Sleep is a sign of a bad design. That being said, its MUCH better than eating 100% of the CPU core time, which is what the for loop above is doing.

A better option is typically to use a WaitHandle, such as a ManualResetEvent, to trigger the continuation of the thread's execution when the "event" (which is the reason to delay) occurs. Alternatively, using a Timer can work as well in many cases.

like image 165
Reed Copsey Avatar answered Dec 28 '22 00:12

Reed Copsey