Does C# stores references to tasks from TPL [dupli

2019-04-10 14:49发布

问题:

This question already has an answer here:

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

Lets assume I run such a code

Task.Factory.StartNew(...).ContinueWith(...);

I don't store reference for neither of two created tasks so can I be sure that they won't be disposed before starting or at the process of executing? If yes then where do reference to these tasks are being held?

回答1:

A reference to a TPL Task is held by the system under two conditions:

  1. The Task is scheduled
  2. The Task is running

Upon completion of the Task and any child tasks, the reference is thrown away. References in your code will behave as expected.


I believe you have some confusion regarding garbage collection and Dispose. This question may enlighten you.

Difference between destructor, dispose and finalize method

Destructor implicitly calls the Finalize method, they are technically same. Dispose is available with those object which implements IDisposable interface...

Should you dispose Tasks?

Stephen Toub says:

No. Don’t bother disposing of your tasks.

http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx