4

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?

Demarsch
  • 1,419
  • 19
  • 39
  • 1
    You can find an answer here: http://stackoverflow.com/questions/2782802/can-net-task-instances-go-out-of-scope-during-run – Yuval Itzchakov Apr 17 '14 at 12:24
  • 1
    Short answer is yes, of course. Will be interesting to see if someone can explain in more detail of course :) – NPSF3000 Apr 17 '14 at 12:24
  • They will NOT be disposed at all. They may be garbage collected, but they wont be disposed. The garbage collector does NOT call `Dispose()` on `IDisposable` objects. You MUST explicitly call `Dispose()` yourself. – Enigmativity Apr 17 '14 at 12:32
  • Actually I meant 'Garbage collected' instead of 'Disposed' – Demarsch Apr 17 '14 at 13:05

1 Answers1

5

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.

https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/

Gusdor
  • 14,001
  • 2
  • 52
  • 64
  • But `Dispose` wont be called unless the finalizer explicitly calls it and there is no guarantee that the finalizer will actually run. – Enigmativity Apr 17 '14 at 12:37
  • 1
    @Enigmativity This article should help you out on that point http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx – Gusdor Apr 17 '14 at 12:39
  • I actually meant 'Garbage collected' instead of 'Disposed' – Demarsch Apr 17 '14 at 13:05
  • @Gusdor - Thanks for the link, but it does change the widespread misconception that the garbage collector calls `Dispose()`. That was my point. – Enigmativity Apr 17 '14 at 23:35
  • *"A reference to a TPL Task is held by the system under two conditions: 1. The Task is scheduled, 2. The Task is running"* <== Do you mean that both conditions must be true, or that at least one must be true? – Theodor Zoulias Dec 02 '20 at 07:01
  • 1
    @Gusdor The link you have shared in both the post and the comment is broken. The blog is [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) – ghd Jun 03 '21 at 10:22
  • 1
    Thanks for that @ghd. I've updated the answer with the correct link. – Gusdor Jun 04 '21 at 12:06