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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With