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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With