Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I await a 'async Task' function if I don't care its return value? [duplicate]

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?

like image 938
codewarrior Avatar asked Mar 29 '17 19:03

codewarrior


1 Answers

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.

like image 180
Stephen Cleary Avatar answered Nov 05 '22 03:11

Stephen Cleary