阻塞直到事件完成 [英] Blocking until an event completes
本文介绍了阻塞直到事件完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何阻止直到异步事件完成?
How can you block until an asynchronous event completes?
这是一种通过在事件处理程序中设置一个标志并轮询该标志来阻止事件被调用的方法:
Here is a way to block until the event is called by setting a flag in the event handler and polling the flag:
private object DoAsynchronousCallSynchronously()
{
int completed = 0;
AsynchronousObject obj = new AsynchronousObject();
obj.OnCompletedCallback += delegate { Interlocked.Increment(ref completed); };
obj.StartWork();
// Busy loop
while (completed == 0)
Thread.Sleep(50);
// StartWork() has completed at this point.
return obj.Result;
}
有没有一种方法可以不进行轮询?
Is there a way to do this without polling?
推荐答案
private object DoAsynchronousCallSynchronously()
{
AutoResetEvent are = new AutoResetEvent(false);
AsynchronousObject obj = new AsynchronousObject();
obj.OnCompletedCallback += delegate
{
are.Set();
};
obj.StartWork();
are.WaitOne();
// StartWork() has completed at this point.
return obj.Result;
}
这篇关于阻塞直到事件完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文