Awaiting a Callback method

  • A+
Category:Languages

I'm calling a third-party API which has a method that looks like this:

myServiceClient.Discover(key, OnCompletionCallback);  public bool OnCompletionCallback(string response) {     // my code } 

My challenge is, I have to call Discover because it does some work under-the-covers that I need. At the same time, I have to wait for Discover to complete before running my custom code. To further complicate matters, I can't just put my code in the OnCompletionCallback handler because I need to call the code above from a Func delegate. In short, I want to do this:

Func<SystemTask> myFunction = async () => {     await myServiceClient.Discover(key);      // my code } 

However, I can't do this because the third-party API uses a callback approach instead of an async/await approach.

Is there some way to make the callback approach work in an async / await world?


If I understand you correctly you can do something like this

public Task<bool> MyAsyncFunction() {     var tcs = new TaskCompletionSource<bool>();      myServiceClient.Discover("somekey", s => {         //........         var res = true;         tcs.TrySetResult(res);         return res;     });      return tcs.Task; } 

Now you can await MyAsyncFunction

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: