3

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

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

1 回答 1

3

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

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

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

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

于 2012-01-09T16:56:47.213 回答