5

Have I in some way delete this Task or it is self-destroyed?

Task.Factory.StartNew(() => { DoSomeJob(); }, TaskCreationOptions.LongRunning);

or it is better to use it like

var t = Task.Factory.StartNew(() => { DoSomeJob(); }, TaskCreationOptions.LongRunning);

and somehow later delete/nullize t?

Thank you!

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 1
    related: [Is it considered acceptable to not call Dispose() on a TPL Task object?](http://stackoverflow.com/questions/3734280/is-it-considered-acceptable-to-not-call-dispose-on-a-tpl-task-object) – Paolo Moretti Oct 12 '12 at 13:43

4 Answers4

6

you do not need to delete it, it will be disposed eventually....

Z .
  • 12,657
  • 1
  • 31
  • 56
3

If you mean can you cancel it, or abort it, or in some other way stop it from running before it finishes; no, not really (as it currently is). You would need to create a cancellation token source, pass the token to the Task, and then the method running in the task would need to periodically check to ensure that it hasn't been canceled.

What you could do is to wait for some period of time and cancel that waiting operation. That would allow you to continue running the "next" task that you need to run. Note that if you did this, without adding the work I discussed above where the method in the task itself checks for deletion, then the method will still run to completion, you'll just stop waiting on it earlier.

Related link

If you are simply worried about cleaning up the resources that the task uses once it's done running, you don't need to worry. It will all be handled automatically.

Related link

Servy
  • 202,030
  • 26
  • 332
  • 449
2

If you want to try and dispose of it yourself, you would have to be careful. If it is still in a running state, you will get this exception:

A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled)

So it is better to use your first example.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
1

Garbage collection will handle the cleanup for you, you don't have to keep the reference t.

Piotr Zierhoffer
  • 5,005
  • 1
  • 38
  • 59