Blocking until an event completes

独自空忆成欢 提交于 2020-12-04 04:04:49

问题


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?


回答1:


    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;
    }



回答2:


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.



来源:https://stackoverflow.com/questions/1523148/blocking-until-an-event-completes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!