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?