2012-05-31 59 views
6

我正在使用一个库进行异步调用,并且当返回响应时,会调用一个回调方法并显示结果。这是一个简单的模式,但我现在遇到了障碍。我如何对异步方法执行多个调用并等待(无阻塞)?当我从所有服务中获取数据时,我想调用自己的回调方法,该方法将获取由异步方法返回的两个(或多个)值。等待多个回调

这里遵循的正确模式是什么?顺便说一句,我不能改变图书馆使用TPL或其他东西...我必须忍受它。

public static void GetDataAsync(Action<int, int> callback) 
{ 
    Service.Instance.GetData(r1 => 
    { 
     Debug.Assert(r1.Success); 
    }); 

    Service.Instance.GetData2(r2 => 
    { 
     Debug.Assert(r2.Success); 
    }); 

    // How do I call the action "callback" without blocking when the two methods have finished to execute? 
    // callback(r1.Data, r2.Data); 
} 

回答

6

你想要的东西就像是CountdownEvent。试试这个(假设你是在.NET 4.0):

public static void GetDataAsync(Action<int, int> callback) 
{ 
    // Two here because we are going to wait for 2 events- adjust accordingly 
    var latch = new CountdownEvent(2); 

    Object r1Data, r2Data;  

    Service.Instance.GetData(r1 => 
    { 
     Debug.Assert(r1.Success); 
     r1Data = r1.Data; 
     latch.Signal(); 
    }); 

    Service.Instance.GetData2(r2 => 
    { 
     Debug.Assert(r2.Success); 
     r2Data = r2.Data; 
     latch.Signal(); 
    }); 

    // How do I call the action "callback" without blocking when the two methods have finished to execute? 
    // callback(r1.Data, r2.Data); 

    ThreadPool.QueueUserWorkItem(() => { 
     // This will execute on a threadpool thread, so the 
     // original caller is not blocked while the other async's run 

     latch.Wait(); 
     callback(r1Data, r2Data); 
     // Do whatever here- the async's have now completed. 
    }); 
} 
2

你可以使用Interlocked.Increment每个异步调用你做。完成后,请致电Interlocked.Decrement并检查零(如果为零),请致电您自己的回拨。您需要在回调委托之外存储r1和r2。