问题
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?
回答1:
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;
}
回答2:
Don't use an asynchronous operation? The whole point behind asynchronous operations is NOT to block the calling thread.
If you want to block the calling thread until your operation completes, use a synchronous operation.
来源:https://stackoverflow.com/questions/1523148/blocking-until-an-event-completes