Search code examples
.netasynchronoustask-parallel-libraryasync-ctp

Wrapping existing async method into TPL-compatiable method


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

Solution

  • 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.