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?
using
if you do not wait for it. And it makes sense to have cancellation only if you do not wait.ContinueWith
on task with a Dispose
call, but is that the way to go?.ForAll(x => Console.Write(x))
?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?
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.