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

2 回答 2

7

你想要的是类似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.
    });
}
于 2012-05-31T02:03:14.100 回答
2

您可以使用Interlocked.Increment您进行的每个异步调用。当一个完成时,调用Interlocked.Decrement并检查是否为零,如果为零,则调用您自己的回调。您需要将 r1 和 r2 存储在回调委托之外。

于 2012-05-31T02:18:53.440 回答