Wrapping existing async method into TPL-compatiable method

268 views Asked by At

How to wrap existing async method that accepts callback function as parameter into Task Parallel Library-compatible method?

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

There are 1 answers

1
Stephen Cleary On BEST ANSWER

I'm assuming that your existing DoAsync method will run asynchronously.

In that case, you can wrap it like this:

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

I don't see how your existing DoAsync method reports asynchronous errors. You can use TaskCompletionSource<T>.TrySetException to report an asynchronous error if necessary.