Can .NET Task instances go out of scope during run

2019-01-11 08:54发布

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.

2条回答
虎瘦雄心在
2楼-- · 2019-01-11 09:18

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-11 09:24

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.

查看更多
登录 后发表回答