When to dispose CancellationTokenSource?

George Mamaladze picture George Mamaladze · Aug 5, 2011 · Viewed 49.4k times · Source

The class CancellationTokenSource is disposable. A quick look in Reflector proves usage of KernelEvent, a (very likely) unmanaged resource. Since CancellationTokenSource has no finalizer, if we do not dispose it, the GC won't do it.

On the other hand, if you look at the samples listed on the MSDN article Cancellation in Managed Threads, only one code snippet disposes of the token.

What is the proper way to dispose of it in code?

  1. You cannot wrap code starting your parallel task with using if you do not wait for it. And it makes sense to have cancellation only if you do not wait.
  2. Of course you can add ContinueWith on task with a Dispose call, but is that the way to go?
  3. What about cancelable PLINQ queries, which do not synchronize back, but just do something at the end? Let's say .ForAll(x => Console.Write(x))?
  4. Is it reusable? Can the same token be used for several calls and then dispose it together with the host component, let's say UI control?

Because it does not have something like a Reset method to clean-up IsCancelRequested and Token field I would suppose it's not reusable, thus every time you start a task (or a PLINQ query) you should create a new one. Is it true? If yes, my question is what is the correct and recommended strategy to deal with Dispose on those many CancellationTokenSource instances?

Answer

Gruzilkin picture Gruzilkin · Sep 18, 2012

Speaking about whether it's really necessary to call Dispose on CancellationTokenSource... I had a memory leak in my project and it turned out that CancellationTokenSource was the problem.

My project has a service, that is constantly reading database and fires off different tasks, and I was passing linked cancellation tokens to my workers, so even after they had finished processing data, cancellation tokens weren't disposed, which caused a memory leak.

MSDN Cancellation in Managed Threads states it clearly:

Notice that you must call Dispose on the linked token source when you are done with it. For a more complete example, see How to: Listen for Multiple Cancellation Requests.

I used ContinueWith in my implementation.