阻止直到事件完成

时间:2009-10-06 01:07:26

标签: c# events asynchronous iasyncresult

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

这是一种阻止事件被调用的方法,方法是在事件处理程序中设置一个标志并轮询标志:

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

有没有办法在没有投票的情况下这样做?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

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

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