3

在异步事件完成之前如何阻塞?

这是通过在事件处理程序中设置标志并轮询标志来阻止直到调用事件的方法:

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

有没有办法在没有轮询的情况下做到这一点?

4

2 回答 2

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;
    }
于 2009-10-06T01:11:13.913 回答
3

不要使用异步操作?异步操作背后的重点不是阻塞调用线程。

如果要在操作完成之前阻塞调用线程,请使用同步操作。

于 2009-10-06T01:11:40.840 回答