Thread.Sleep () Impact in a Continuous Loop

Consider the following code snippet:

void MyRunningThread() { while(counter>0) // counter is a Class member that can get modified from external //threads { Thread.Sleep(2000); } } 

Suppose I run Thread from the above function.

Now, is it bad to have an infinite loop like this inside Thread? I added Thread.Sleep () with the assumption that context switching to this function will occur at a lower frequency due to Sleep mode and, therefore, reduce the consumption of resources of this Thread.

Can anyone check my scores.

+4
source share
3 answers

This is far from optimal when wasting a stream.

You should use a timer or WaitHandle or something else. Without details, it is impossible to be precise.

But your current approach is not catastrophic or anything else, provided that this other thread uses lock or InterLocked to change the counter.

+4
source

Try using System.Threading.SpinWait instead of sleeping, this article explains how to use it http://www.emadomara.com/2011/08/spinwait-and-lock-free-code.html

+2
source

Could you tell us more about your problem? Why would you wait in another thread? In any case, if you need to wait until some counter becomes zero, you can use CountdownEvent

0
source

All Articles