Can .NET Task instances go out of scope during run?

C#.NetGarbage CollectionTaskTask Parallel-Library

C# Problem Overview


If I have the following block of code in a method (using .NET 4 and the Task Parallel Library):

var task = new Task(() => DoSomethingLongRunning());
task.Start();

and the method returns, will that task go out of scope and be garbage collected, or will it run to completion? I haven't noticed any issues with GCing, but want to make sure I'm not setting myself up for a race condition with the GC.

C# Solutions


Solution 1 - C#

Update:

After I answered this question (a long time ago!) I found out that it's not true that Tasks will always run to completion - there's a small, let's say "corner" case, where tasks may not finish.

The reason for that is this: As I have answered previously, Tasks are essentially threads; but they are background threads. Background threads are automatically aborted when all foreground threads finish. So, if you don't do anything with the task and the program ends, there's a chance the task won't complete.

You should always await on tasks. More information can be found on the excellent answer Jon gave me.


Original:

Task are scheduled to the ThreadPool, meaning that they are essentially threads¹ (actually, they encapsulate threads).

From the Thread documentation:

> It is not necessary to retain a > reference to a Thread object once you > have started the thread. The thread > continues to execute until the thread > procedure is complete.

So, no, there is no need to retain a reference to it.

Also, the documentation states that the preferred way to create a Task is to use it's factory:

> You can also use the StartNew method > to create and start a task in one > operation. This is the preferred way > to create and start tasks if creation > and scheduling do not have to be > separated (...)

Hope it helps.


¹ Accordingly to the documentation:

> A task represents an asynchronous > operation, and in some ways it > resembles the creation of a new thread > or ThreadPool work item, but at a > higher level of abstraction.

Solution 2 - C#

The task will run to completion. Even if there aren't any other references to it (not being rooted I believe is the term), the thread pool will still hold a reference to it, and prevent it from being Garbage Collected at least (I say at least, because even after it completes, there is no guarantee that it will be Garbage Collected) until completion.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHankView Question on Stackoverflow
Solution 1 - C#Bruno BrantView Answer on Stackoverflow
Solution 2 - C#kemiller2002View Answer on Stackoverflow