Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I responsible for cleaning up after a Task created with the TaskCreationOptions.LongRunning flag?

When you create a Task while specifying TaskCreationOptions.LongRunning a new thread is created specifically for the task. If you do not specify the TaskCreationOptions.LongRunning then the threadpool is used.

Please correct me if I'm wrong but if the threadpool is used you do not need to dispose() the task (as long as you have not used any synchronisation objects inside the task, like Wait() on a child task).

If this is the case, am I responsible for cleaning up the extra thread created by using the TaskCreationOptions.LongRunning flag?

If so is the following an acceptable pattern:

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

task.ContinueWith(x => task.Dispose());

Notice how, the ContinueWith does not have a TaskContinuationOptions.LongRunning, so it should use the threadpool.

That being said, however, I have read that the thread that moves the state of the task to Completed, Faulted or Cancelled has a high change of running the continuation.

If someone could shine some light on this I would really appreciate it.

like image 729
InvertedAcceleration Avatar asked Oct 13 '11 13:10

InvertedAcceleration


1 Answers

Definitely don't call Dispose() in a continuation - when are you going to dispose the continuation task?

AFAIK, the only reason Task is disposable is to clear up the wait handle created if you wait on the task. If you don't wait on the task, the wait handle will never be created. In any case, the finalizer will clear up eventually.

Also, if a new thread is created by the Task, it will clean up after itself.

like image 191
Nick Butler Avatar answered Sep 21 '22 21:09

Nick Butler