5

如何将 Task.Factory.FromAsync 工厂用于通过“out”参数返回多个值的 end 方法?

begin 方法有这个签名:

public virtual System.IAsyncResult BeginGetCaseStatus(int CaseOID, int ClientOID, System.AsyncCallback @__Callback, object @__UserData)

结束方法是:

public virtual void EndGetCaseStatus(System.IAsyncResult @__AsyncResult, out DTGenericCode[] BasicStatus, out DTGenericCode[] ARStatus)

我可以一些如何使用:

public Task<?> GetCaseStatusAsync(int CaseOID, int ClientOID)
{
    return Task.Factory.FromAsync  (BeginGetCaseStatus(CaseOID, ClientOID, null, null), EndGetCaseStatus(?, ?));
}
4

2 回答 2

7

endMethod参数FromAsync()是一个委托,因此您可以使用 lambda 将out-form 转换为方法的正常形式-End。就像是:

private static Task<Tuple<DTGenericCode[], DTGenericCode[]>> GetCaseStatusAsync(
    int CaseOID, int ClientOID)
{
    return Task.Factory.FromAsync(
        BeginGetCaseStatus, ar =>
        {
            DTGenericCode[] basicStatus;
            DTGenericCode[] arStatus;

            EndGetCaseStatus(ar, out basicStatus, out arStatus);

            return Tuple.Create(basicStatus, arStatus);
        },
        CaseOID, ClientOID, null);
}

尽管您可能想使用自定义类型而不是Tuple.

于 2013-10-04T00:36:12.533 回答
7

没有任何FromAsync过载可以解决这个问题。最好的选择可能是构建自己的包装器:

public class ResultStatus
{
     public ResultStatus(DTGenericCode[] basicStatus, DTGenericCode[] arStatus)
     {
         this.BasicStatus = basicStatus;
         this.ARStatus = arStatus;
     }
     public DTGenericCode[] BasicStatus { get; private set; }
     public DTGenericCode[] ARStatus { get; private set; }
}

public Task<ResultStatus> GetCaseStatusAsync(int CaseOID, int ClientOID)
{
     var tcs = new TaskCompletionSource<ResultStatus>();
     theClass.BeginGetCaseStatus(CaseOID, ClientOID, iar =>
             {
                 DTGenericCode[] bs;
                 DTGenericCode[] as;
                 theClass.EndGetCaseStatus(iar, out bs, out as);

                 tcs.SetResult(new ResultStatus(bs, as));
             }, null);

     return tcs.Task;
}
于 2013-10-03T23:18:08.917 回答