Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22114

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 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.

Upvotes: 4

Views: 2652

Answers (3)

Emad Omara
Emad Omara

Reputation: 532

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

Upvotes: 2

the_joric
the_joric

Reputation: 12261

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

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273784

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.

Upvotes: 4

Related Questions