This question already has an answer here:
- Do I have to await an async method? 2 answers
- Fire-and-forget with async vs “old async delegate” 4 answers
- What is the purpose of “return await” in C#? 7 answers
- C# Asynchronous call “invoke and forget” 3 answers
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?
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 andawait
it later.Not awaiting the task is "fire and forget", which literally means:
It's very rare to have a true fire-and-forget scenario.
After the
Task
returned by the async function completes, yes.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.