Wait until there is an asynchronous method

How can I wait for the void async method to finish working?

for example, I have a function as shown below:

 async void LoadBlahBlah() { await blah(); ... } 

now I want to make sure everything is loaded before proceeding elsewhere.

+67
c # asynchronous windows-8 windows-store-apps
Nov 29 '12 at 23:25
source share
5 answers

It is best practice to mark the async void function only if it is a fire and forget method, if you want to wait, you should mark it as async Task .

If you still want to wait, then wrap it like this: await Task.Run(() => blah())

+78
Nov 30 '12 at 2:17
source share

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

+49
Nov 30
source share

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

If the method cannot be returned to return a Task (for example, it is an event handler), you can use SemaphoreSlim to get the method signal when it is about to exit. Think about it in the finally block.

+13
Nov 30 '12 at 2:21
source share

You don’t have to do anything manually, the await keyword pauses the function until blah() returns.

 private async void SomeFunction() { var x = await LoadBlahBlah(); <- Function is paused //do more stuff when LoadBlahBlah() returns } private async Task<T> LoadBlahBlah() { return await blah(); <- function is paused } 

T - object type blah() returns

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

+2
Nov 30 '12 at 1:24
source share

execute the AutoResetEvent function, call the function, then wait for AutoResetEvent, and then set it to async void when you know that it is done.

You can also wait for the job that is returning from your void async arithmetic

+2
Aug 23 '13 at 20:34
source share



All Articles