Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async to execute callback delegate

I have a callback function which needs to takes several seconds to process and should be a async method, but I can't find a way to execute this async callback by await because it must be a Delegate param in the calling method. Here is some piece of code:

async Task Callback(){//do some callback..}
async Task DoSomething(Func<Task> callback){//I want to execute the callback like: await callback();}
async void Main(){ DoSomething(Callback);}

Sorry for my poor english, any idea to do that? Thanks!

like image 665
hellojiaru Avatar asked Dec 20 '25 11:12

hellojiaru


1 Answers

You will have to await first call itself.

change

async void Main(){ DoSomething(Callback);}

to

async void Main(){ await DoSomething(Callback);}

After that It should work, I tested with your sample code. Please verify at your end.

class Program
{
    static void Main(string[] args)
    {
       (new Test()).Main();
       Console.ReadKey();
    }
}

public class Test
{

    async Task Callback()
    {
        Console.WriteLine("I'm in callback");
    }
    async Task DoSomething(Func<Task> callback)
    {
        Console.WriteLine("I'm in DoSomething");
        await callback();
    }
    public async void Main()
    {
        Console.WriteLine("I'm in Main");
        await DoSomething(Callback);
        Console.WriteLine("Execution completed");
    }
}

Here is output

enter image description here

like image 197
Shashi Bhushan Avatar answered Dec 23 '25 01:12

Shashi Bhushan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!