Lock until event ends

How can you block until the completion of the asynchronous event?

Here is a way to block until an event is raised 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 any way to do this without polling?

+3
source share
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;
    }
+5
source

Do not use asynchronous operation? The whole point of asynchronous operations is NOT to block the calling thread.

If you want to block the calling thread until the operation completes, use the synchronous operation.

+3
source

Source: https://habr.com/ru/post/1719347/


All Articles