How to wait for a boolean without looping (using any kind of wait / semaphore / event / mutex, etc)

Ignacio Soler Garcia picture Ignacio Soler Garcia · Sep 13, 2012 · Viewed 30.9k times · Source

I need to stop a thread until another thread sets a boolean value and I don't want to share between them an event.

What I currently have is the following code using a Sleep (and that's the code I want to change):

while (!_engine.IsReadyToStop())
{
    System.Threading.Thread.Sleep(Properties.Settings.Default.IntervalForCheckingEngine); 
}

Any ideas?

EDIT TO CLARIFY THINGS:

There is an object called _engine of a class that I don't own. I cannot modify it, that's why I don't want to share an event between them. I need to wait until a method of that class returns true.

Answer

MoonStom picture MoonStom · Dec 12, 2015

SpinWait.SpinUntil is the right answer, regardless where you're gonna place this code. SpinUntil offers "a nice mix of spinning, yielding, and sleeping in between invocations".