我发现自己编写过几次这种类型的代码。
for (int i = 0; i < 10; i++)
{
if (Thing.WaitingFor())
{
break;
}
Thread.Sleep(sleep_time);
}
if(!Thing.WaitingFor())
{
throw new ItDidntHappenException();
}
它看起来像糟糕的代码,是否有更好的方法/这是糟糕设计的症状?
最佳答案
实现此模式的更好方法是让您的 Thing
对象公开一个消费者可以等待的事件。例如 ManualResetEvent
或 AutoResetEvent
。这大大简化了您的消费者代码如下
if (!Thing.ManualResetEvent.WaitOne(sleep_time)) {
throw new ItDidntHappen();
}
// It happened
Thing
端的代码也并不复杂。
public sealed class Thing {
public readonly ManualResetEvent ManualResetEvent = new ManualResetEvent(false);
private void TheAction() {
...
// Done. Signal the listeners
ManualResetEvent.Set();
}
}
关于c# - c#有更好的等待模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997291/