Should I await a 'async Task' function if

2019-02-19 06:46发布

Do I need to await a async Task function if it doesn't return anything? Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

Task DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do something, but doesn't return values.
    });
}

void Test()
{
    DoSomethingAsync();  // should I await?

    // Do other things, totally not related to the async function
    Console.WriteLine("aaa");
}

In above example, if I await DoSomethingAsync() in Test(), will that cause the following code Console.WriteLine be wrapped in delegate and defer executed only when the async task is done?

2条回答
迷人小祖宗
2楼-- · 2019-02-19 07:06

Do I need to await a async Task function if it doesn't return anything?

Generally, yes. Not only does this allow you to detect when it completes, it also allows you to respond to any errors. You can, if you wish, store the Task object and await it later.

Not awaiting the task is "fire and forget", which literally means:

  • You don't care whether it completes.
  • You don't care when it completes.
  • You don't care whether it is successful or fails.

It's very rare to have a true fire-and-forget scenario.

Will that cause the following code be wrapped in a delegate and executed after the async Task function returns?

After the Task returned by the async function completes, yes.

查看更多
不美不萌又怎样
3楼-- · 2019-02-19 07:08

If you don't and your program exits before the task completes, you're screwed. You at least would want to await all/any of those tasks before allowing to exit. You should also consider any implications of multiple instances of those tasks running at the same time if you don't know when the unawaited one will finish. Exceptions also can't be relied on to bubble up to the caller.

A better way might be to always await at the top level caller only await at the latest possible moment when you really need to (like if the app is about to exit)

To your question about Console.WriteLine - yes it will only print after completion IF you await the previous line. If you don't await, it will race with the code executing in the task.

查看更多
登录 后发表回答