Blocking until an event completes
Asked Answered
D

2

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?

Distillation answered 6/10, 2009 at 1:7 Comment(0)
F
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;
    }
Frontwards answered 6/10, 2009 at 1:11 Comment(0)
A
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.

Acrylic answered 6/10, 2009 at 1:11 Comment(4)
Unless the API/Object does not expose a synchronous call (in fact I'm working with one right now that doesn't).Frontwards
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.Liggett
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.Acrylic
@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.Frontwards

© 2022 - 2024 — McMap. All rights reserved.