开发者

Impact of Thread.Sleep() in a continuous loop

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜