views:

92

answers:

2

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?

+3  A: 
    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;
    }
ctacke
+3  A: 

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.

Justin Niessner
The correct answer. +1
spender
Unless the API/Object does not expose a synchronous call (in fact I'm working with one right now that doesn't).
ctacke
In the simplest of terms, you might be correct, but what if you want to do the asynchronous operation X number of times and block the caller until all X are done? If that's what the OP is trying to ask I would probably rephrase the question, but when I read the question that's the first thing that jumps out at me.
Joseph
If the API doesn't expose a synchronous call, I'd take a serious look at why you want to block the calling thread while the method completes. Doesn't mean it's wrong, but it definitely deserves a second look.
Justin Niessner
@Justing: yes, it certainly does deserve a second look, but there are definitely APIs that have this behavior. I consider the APIs themselves to be a bit flawed, but I don't get to choose how they are written, I simply have to consume them.
ctacke