How can I call the async method inside an anonymous delegate?

My function accepts a delegate as an input parameter.

public delegate bool Callback();

public static class MyAPI
{
     public static handle(Callback callback) {
           ... 
     }
}

So I am calling api with an anonymous delegate like this

MyAPI.handle(delegate
{
    // my implementation
});

My question is: how can I call the async method on my anonymous deletion?

MyAPI.handle(delegate
{
    // my implementation
    await MyMethodAsync(...);
});

Am I getting a message that the 'wait' statement can only be used in the asynchronous anonymous method '?

The MyAPI.handle () function expects only a non async delegate. I can not change this method. How can I fix my problem?

Thanks.

+4
source share
2 answers

You can call the asynchronous method by passing the async lambda expression:

MyAPI.handle(async () =>
{
    // my implementation
    await MyMethodAsync(...);
});
+8
source
MyAPI.handle(async () =>
{
    // my implementation
    await MyMethodAsync(...);
});
+3
source

Source: https://habr.com/ru/post/1614783/


All Articles