Reputation: 15860
I need some way to do the following efficiently in C#:
Make program execution stop until certain value is changed.
Note: I do not want to make it with a while loop to avoid wasting cpu power..
Edit: And I want it to respond as quickly as possible after value has changed..
Edit: This will be inside my class method that is called by another code, however the value to be checked is inside my class... The method is supposed to wait until others code evaluate and change my value.. then it must continue to do its work.. unfortunately this is done many times(so I need to care for performance)
Upvotes: 6
Views: 3962
Reputation: 55936
while(some-condition-here)
{
Thread.CurrentThread.Sleep(100); // Release CPU for 100ms
}
It's called spin-sleeping I think. Of course you can adjust the 100 to whatever you feel is fit. It's basically the timeout for each check.
There's other ways of doing it, but this is the easiest and it's quite efficient.
It's actually referenced in this e-book:
Threading in C# by Joseph Albahari: Part 2: Basic Synchronization
Upvotes: 6
Reputation: 1437
If the value you're waiting for is set somewhere else in the same application you can use a wait handle:
AutoResetEvent waitHandle = new AutoResetEvent();
...
//thread will sleep here until waitHandle.Set is called
waitHandle.WaitOne();
...
//this is where the value is set
someVar = someValue;
waitHandle.Set();
(note that the WaitOne and Set have to occur on separate threads as WaitOne will block the thread it is called on)
If you don't have access to the code that changes the value, the best way to do it is, as others have said, use a loop to check if the value has changed and use Thread.Sleep() so you're not using as much processor time:
while(!valueIsSet)
{
Thread.Sleep(100);
}
Upvotes: 7