在异步事件完成之前如何阻塞?
这是通过在事件处理程序中设置标志并轮询标志来阻止直到调用事件的方法:
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;
}
有没有办法在没有轮询的情况下做到这一点?