Is it considered acceptable to not call Dispose() on a TPL Task object?

There is a discussion about this in the MSDN forums.

Stephen Toub, a member of the Microsoft pfx team has this to say:

Task.Dispose exists due to Task
potentially wrapping an event handle
used when waiting on the task to
complete, in the event the waiting
thread actually has to block (as
opposed to spinning or potentially
executing the task it’s waiting on).
If all you’re doing is using
continuations, that event handle will
never be allocated

it’s likely better to rely on finalization to take care of things.

Update (Oct 2012)
Stephen Toub has posted a blog titled Do I need to dispose of Tasks? which gives some more detail, and explains the improvements in .Net 4.5.

In summary: You don’t need to dispose of Task objects 99% of the time.

There are two main reasons to dispose an object: to free up unmanaged resources in a timely, deterministic way, and to avoid the cost of running the object’s finalizer. Neither of these apply to Task most of the time:

  1. As of .Net 4.5, the only time a Task allocates the internal wait handle (the only unmanaged resource in the Task object) is when you explicitly use the IAsyncResult.AsyncWaitHandle of the Task, and
  2. The Task object itself doesn’t have a finalizer; the handle is itself wrapped in an object with a finalizer, so unless it’s allocated, there’s no finalizer to run.

Leave a Comment