最好的方法"块QUOT;直到某些条件得到满足最好的、条件、方法、QUOT

2023-09-04 08:02:05 作者:薄荷糖、透心凉

我想创造一些方法,以通用的方式来使用,是它会阻止(除非某个超时),直到给定的条件得到满足。

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.

在code中的使用将是类似于:

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.

在当前实现,我初始化一次性计时器在超时到期。我运行一个while循环,并检查是否定时器超时与否,如果它没有抛出异常。

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 ?

推荐答案

看一看阿尔巴哈利的线程文章,特别是基本同步部分和ManualResetEvent和AutoResetEvent.这会给你有关.NET中的信令结构是个好主意。

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.