Wait for a void async method
How can I wait for a void async
method to finish its job?
for example, I have a function like below:
async void LoadBlahBlah()
{
await blah();
...
}
now I want to make sure that everything has been loaded before continuing somewhere else.
Solution 1:
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())
Solution 2:
If you can change the signature of your function to async Task
then you can use the code presented here
Solution 3:
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.
Solution 4:
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