如何包装异步方法的结果

How to wrap result of an async method

如何将异步方法的结果包装到我自己的包装器 class (MyEnvelop) 中,并且 return 它像任务一样?

我使用自定义信封 class 将数据访问组件的结果 return 返回业务层。 这适用于同步方法,但我如何 return 在异步模式下输入 MyEnvelope 的结果?

已更新 代码示例:

  public async Task<MyEnvelope<Customer>> FindAsync(params object[] keyValues)
    {
        using (var nw = new NWRepository())
        {
        Customer result = await  nw.DoSomethingAsync<Customer>(keyValues);
        return // here I would like to return new MyEnvelope<Customer>(result)
               // wrapped in Task as shown in the signature
                }
            }

你想做的是:

public async Task<MyEnvelope<Customer>> FindAsync(params object[] keyValues)
{
    using (var nw = new NWRepository())
    {
         Customer c = await  nw.FindAsync<Customer>(keyValues);
          return new MyEnvelope<Customer>(c);
    }
 }

然后你像这样调用方法:

MyEnvelope<Customer> customer = await FindAsync(p1, p2, p3);

记住 await 将 return 类型为 TTask<T>Result 而不是 Task 对象本身。

无法完成,因为您需要解决任务才能将其传递给 MyEnvelope。您可以获得的最接近的是删除 async/await 关键字,该关键字解包任务并获得 Task<Customer>.

public Task<Customer> FindAsync(params object[] keyValues)
{
    using (var nw = new NWRepository())
    {
        return nw.DoSomethingAsync<Customer>(keyValues)
    }
}