开发者

Impact of Thread.Sleep() in a continuous loop

开发者 https://www.devze.com 2023-03-23 10:59 出处:网络
Consider the following piece of code: void MyRunningThread() { while(counter>0) // counter is a Class member that can get modified from external//threads

Consider the following piece of code:

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

Suppose I start a Thread on the 开发者_Go百科above function.

Now, is it a bad to have a never ending loop like this inside a Thread? I have added Thread.Sleep() with the assumption that context switching to this function will occur at a less frequency due to the Sleep and hence reduce Resource consumption by this Thread.

Could someone verify my points.


It is far from optimal, wasting a Thread .

You should consider using a Timer or a WaitHandle or something. Without more details it's not possible to be precise.

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


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


Could you elaborate your problem more? Why do you need to wait in another thread? Anyway, if you need to wait until some counter becomes zero you may consider to use CountdownEvent

0

精彩评论

暂无评论...
验证码 换一张
取 消