【问题标题】:Wrapping existing async method into TPL-compatiable method将现有的异步方法包装到与 TPL 兼容的方法中
【发布时间】:2012-01-09 16:45:02
【问题描述】:

如何将接受回调函数作为参数的现有异步方法包装到兼容任务并行库的方法中?

// Existing method
void DoAsync(Action<string> callback) {
    ...
}

// The desired method should have similar prototype
Task<string> DoAsync() {
    // Internally this method should call existing
    // version of DoAsync method (see above)
}

【问题讨论】:

    标签: .net asynchronous task-parallel-library async-ctp


    【解决方案1】:

    我假设您现有的 DoAsync 方法将异步运行。

    在这种情况下,你可以这样包装它:

    Task<string> DoAsyncTask()
    {
      var tcs = new TaskCompletionSource<string>();
      DoAsync(result => tcs.TrySetResult(result));
      return tcs.Task;
    }
    

    我看不到您现有的 DoAsync 方法如何报告异步错误。如有必要,您可以使用TaskCompletionSource&lt;T&gt;.TrySetException 报告异步错误。

    【讨论】:

    • 谢谢,正是需要,看起来很不错!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多