开发者

C# stop and continue

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 quick开发者_StackOverflow社区ly 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)


Monitor.Wait and Monitor.Pulse


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);
}


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


You can use the Observer design pattern. It is designed to solve problems like yours.

This pattern mainly contains a subject and an observer. You can have it to respond to any change and very quickly.

You can find more information and sample code here


Read this article http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml

See also http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx which works for some counting situations.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜