views:

112

answers:

2

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.

+6  A: 

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.

Kevin
Yes, `rooted` is the correct term. As long as *something* has a valid (live) reference to the task instance it will not be eligible for collection. In this case, the thread pool itself will hold that reference until the thread completes.
Scott Dorman
To be more accurate, the TPL's task scheduler will have a reference to the task while it is running. Without out that reference, the task might be garbage collected, but that won't stop the code that runs from finishing.
Steven
+3  A: 

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.

Bruno Brant