3

am using a synchronous 3rd function which I cannot modify, such as:

public void startDoSth(Action<string> onDone)

startDoSth spawn a new thread to do the job, and returns immediately, and when the thing is done, my onDone function would be called.

I'd like to write an asynchronous method like below to wrap it:

public async Task<string> doSthAsync();

So, someone can call it like this:

string s = await doSthAsync()
onDone(s)

In doSthasync() I call startDoSth() to do the real thing. But I have no idea how to write the doSthAsync().

Could anyone tell if it is possible and how to do it? Thanks a lot.

Yongyi
  • 327
  • 2
  • 12

1 Answers1

6

You can use TaskCompletionSource to convert that into TAP:

Task<string> DoSthAsync()
{
    var tcs = new TaskCompletionSource<string>();
    startDoSth(tcs.SetResult);
    return tcs.Task;
}

SetResult completes the returned Task (and sets the result), so that can be passed as the callback function.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35