Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

    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;
    }
like image 188
ctacke Avatar answered Dec 04 '25 07:12

ctacke


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.

like image 41
Justin Niessner Avatar answered Dec 04 '25 07:12

Justin Niessner