3

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 Answers2

4
    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
  • 66,480
  • 18
  • 94
  • 155
3

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
  • 242,243
  • 40
  • 408
  • 536
  • 2
    Unless the API/Object does not expose a synchronous call (in fact I'm working with one right now that doesn't). – ctacke Oct 06 '09 at 01:15
  • 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 Oct 06 '09 at 01:16
  • 1
    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 Oct 06 '09 at 01:17
  • 1
    @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 Oct 06 '09 at 01:34