Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

async-await

I have a function takes a delegate as input parameter.

public delegate bool Callback();

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

So I call the api with an anonymous delegate like this

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

My question is how can i call an async method in my anonymous delegate?

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

I get an error saying the 'await' operator can only be used within async anonymous method'?

The function MyAPI.handle() only expect a non async delegate. I can't change that method. How can I fix my problem?

Thank you.

like image 656
n179911 Avatar asked Nov 06 '15 18:11

n179911


People also ask

Can anonymous functions be async?

Description. An async function expression is very similar to, and has almost the same syntax as, an async function statement . The main difference between an async function expression and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions.

Can you call an async method without await?

The current method calls an async method that returns a Task or a Task<TResult> and doesn't apply the Await operator to the result. The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete.

Which method calls the async task?

A synchronous method calls an async method, obtaining a Task . The synchronous method does a blocking wait on the Task .


1 Answers

You could call an asynchronous method by passing an async lambda expression:

MyAPI.handle(async () =>
{
    // my implementation
    await MyMethodAsync(...);
});
like image 52
Christos Avatar answered Nov 14 '22 10:11

Christos