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.
TaskContinuationOptions.LongRunningis a hint to the Task factory/scheduler, things are not so fixed as you portray it.I would expect the
ContinueWithto be executed on the same (longRunning) Thread, that may or may not be running on the ThreadPool.And as far as I know cleanup of Tasks is automatic, so I wouldn’t bother with Dispose() here.