Are there any benefits for using a CancellationTokenSource over a volatile boolean field for signalling a Task
to finish?
The CancellationTokenSource is the 'thing' that issues the cancellation, for whatever reason. It needs a way to 'dispatch' that cancellation to all the CancellationToken 's it has issued. That's how, for example, ASP.NET can cancel operations when a request is aborted.
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.
Always call Dispose before you release your last reference to the CancellationTokenSource. Otherwise, the resources it is using will not be freed until the garbage collector calls the CancellationTokenSource object's Finalize method.
Yes, you can reuse CancellationTokens. A CancellationTokenSource is used to cancel a set of processes. All processes associated with a particular CancellationTokenSource will use one CancellationToken among them.
Of course yes. There are many. I'll list few.
CancellationToken
supports callbacks. You can be notified when the cancellation is requested.CancellationToken
supports WaitHandle
which you could wait for indefinitely or with a timeout.CancellationToken
using CancellationTokenSource.CancelAfter
method.CancellationToken
to another, so that when one is cancelled another can be considered as cancelled.Task
if you mean System.Threading.Tasks.Task
a volatile boolean cannot transition the state of the Task to cancelled but CancellationToken
can.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With