Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a void async method

People also ask

Can we return void in async method?

In short, if your async method is an event handler or a callback, it's ok to return void .

Can we use async with void?

Async Task methods enable easier error-handling, composability and testability. The exception to this guideline is asynchronous event handlers, which must return void. This exception includes methods that are logically event handlers even if they're not literally event handlers (for example, ICommand.

Can we use async void in C#?

You use the void return type in asynchronous event handlers, which require a void return type. For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited.


Best practice is to mark function async void only if it is fire and forget method, if you want to await on, you should mark it as async Task.

In case if you still want to await, then wrap it like so await Task.Run(() => blah())


If you can change the signature of your function to async Task then you can use the code presented here


The best solution is to use async Task. You should avoid async void for several reasons, one of which is composability.

If the method cannot be made to return Task (e.g., it's an event handler), then you can use SemaphoreSlim to have the method signal when it is about to exit. Consider doing this in a finally block.


You don't really need to do anything manually, await keyword pauses the function execution until blah() returns.

private async void SomeFunction()
{
     var x = await LoadBlahBlah(); <- Function is not paused
     //rest of the code get's executed even if LoadBlahBlah() is still executing
}

private async Task<T> LoadBlahBlah()
{
     await DoStuff();  <- function is paused
     await DoMoreStuff();
}

T is type of object blah() returns

You can't really await a void function so LoadBlahBlah() cannot be void