Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Action method call to async Action method call

I've this method

public void Execute(Action action) {     try     {         action();     }     finally     {     } } 

and I need to convert it to an async method call like this one

public async Task ExecuteAsync(Action action) {     try     {         await action();     }     finally     {     } } 

The problem with the code above is that the compiler issue the following error

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

like image 575
vcRobe Avatar asked Nov 26 '15 14:11

vcRobe


People also ask

Can an action be async?

For example, action=getstatus is a synchronous action. Actions that can take a significant time to complete are usually asynchronous. These actions are asynchronous because otherwise requests might time out before Media Server is able to process them.

What happens when you call async method without await?

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. In most cases, that behavior isn't expected.

How do you call async method in MVC action?

In the File menu, click New Project. In the "New Project" dialog box, under Project types, expand Visual C#, and then click "Web". In the Name box, type "Async", then click on Ok. Now, in the dialog box, click on "MVC" under the ASP.NET 4.5.

When would you use asynchronous actions?

Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.


1 Answers

If you want to await on a delegate, it has to be of type Func<Task> or Func<Task<T>>. An Action is equivalent into a void Action() named method. You can't await on void, yet you can await Task Func() or Task<T> Func:

public async Task ExecuteAsync(Func<Task> func) {     try     {         await func();     }     finally     {     } } 

If this can't be done, it means that internally the method isn't truly asynchronous, and what you actually want to do is execute the synchronous delegate on a thread-pool thread, which is a different matter, and isn't really executing something asynchronously. In that case, wrapping the call with Task.Run will suffice.

like image 164
Yuval Itzchakov Avatar answered Oct 06 '22 00:10

Yuval Itzchakov