Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaiting a Callback method

Tags:

c#

async-await

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?

like image 363
Some User Avatar asked May 01 '18 20:05

Some User


People also ask

Can we use await in callback function?

The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in . then() and .

What is callback method?

Android Callback Listeners Example: Android maintains the interaction between the end-user and the application using the widely used Listener Design Pattern. All the UI components, like a button, inherit from the View class, which in turns implements the Callback interface from android. graphics.

Can a callback be async?

Simply taking a callback doesn't make a function asynchronous. There are many examples of functions that take a function argument but are not asynchronous. For example there's forEach in Array. It iterates over each item and calls the function once per item.


1 Answers

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

like image 169
Eser Avatar answered Oct 14 '22 06:10

Eser