简体   繁体   中英

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.

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.

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.

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.

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.

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.

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.

I've read all the solutions of the thread and it's really complicated... The easiest solution is to return something like a bool:

async bool LoadBlahBlah()
{
    await blah();
    return true;
}

It's not mandatory to store or chekc the return value. You can juste do:

await LoadBlahBlah();

... and you can return false if something goes wrong.

You can simply change the return type to Task and call await Task.CompletedTask at the end of the function, eg:

async Task MyFunction() {
    await AnotherFunction();

    await Task.CompletedTask;
}

I find this simpler than wrapping the whole function body in a call to Task.Run(() => {... }); .

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

LoadBlahBlah().Wait();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM