sam
sam

Reputation: 1241

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

Upvotes: 3

Views: 260

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456887

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.

Upvotes: 3

Related Questions