Best method to “block” until certain condition is met

别等时光非礼了梦想. 提交于 2020-02-03 04:00:09

问题


I would like to create some method to be used in a generic way, were it would block (unless a certain timeout expires) until a given condition is met.

The usage in code would be something similar to:

WaitUntil( condition );

I have tried implementing it using a While ( .. ) loop, however this seems like a waste.

In current implementation, i am initializing a 'one-off' timer that expires at TIMEOUT. I am running a while loop, and checking if the timer has timed out or not, throwing an exception if it did.

Are there any simple yet effective techniques for implementing such a method ?


回答1:


Blocking for a condition can work (I tend to use Monitor for that personally), however, in most cases I would advise coding in a more async way here, meaning: rather than waiting, you register some kind of callback to occur when the condition happens. This could be via an event, or more recently a Task with continuation (ContinueWith). In c# 5 this is further extended with the "await" metaphor that makes this transparent, I.e.

var foo = StartSomeWork();
...
var result = await foo;
Console.WriteLine(result);

This looks like it is blocking at the "await" - but it is in fact the exact opposite (assuming the task isn't already complete); this registers a continuation that is invoked when the data becomes available, most likely on a different thread.




回答2:


Have a look at Albahari's threading article, especially the basic synchronization part and the ManualResetEvent and AutoResetEvent. This will give you a good idea about signalling constructs in .NET.



来源:https://stackoverflow.com/questions/8771364/best-method-to-block-until-certain-condition-is-met

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!