When using Async/Await in C# are tasks terminated automatically when program exits?

Viewed 641

If I have called multiple async functions that are still being awaited, and the program exits on the main thread, are the tasks still being awaited cleaned up automagically? Or, do I need to ensure tasks are manually cleaned up when the program exits?

Asking specifically when calling async functions, not using new Thread().

Also, in this specific case, Task is referring to System.Threading.Tasks.Task generated when calling an async function and awaiting a result.

Can't seem to find the answer in MSDN (unless I'm looking in the wrong place).

2 Answers

are the tasks still being awaited cleaned up automagically?

If the tasks are awaited, the program is not going to exit before the tasks are completed. So if the program exits, this means that the tasks are not awaited. Or that they are awaited inside a task which is itself not awaited. Or that they are awaited inside an async void method, which is not awaited by definition (an async void method returns nothing that can be awaited).

So I am assuming that you are dealing with non-awaited tasks, or in other words with fire-and-forget tasks. These tasks in most cases are running on threads having the IsBackground property equal to true, or not running on any thread at all. These tasks will be terminated automatically, at an arbitrary execution point. It is not impossible however to start a task that runs on a foreground thread, in which case the program will terminate when the task completes, or when the program is killed from the task manager.

https://medium.com/@hasangi/lets-talk-about-parallelism-in-net-baby-2a69ba53f986

Threads are created as foreground processes by default(can be set to run in the background) and Tasks are created as background processes. An application will not terminate when any foreground processes are running. However, an application will terminate when all foreground processes complete even though when background processes are running. Hence a Task will terminate even without completing.

If we can't create a task running in a foreground thread then the answer is yes, non-awaited tasks will always be terminated on program exit.

Related