Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CancellationTokenSource vs. volatile boolean

Are there any benefits for using a CancellationTokenSource over a volatile boolean field for signalling a Task to finish?

like image 434
Yoav Avatar asked May 04 '15 07:05

Yoav


People also ask

What is difference between CancellationTokenSource and CancellationToken?

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.

What is a CancellationTokenSource?

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.

Should CancellationTokenSource be disposed?

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.

Can you reuse CancellationTokenSource?

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.


1 Answers

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.
  • You can schedule the cancelation of CancellationToken using CancellationTokenSource.CancelAfter method.
  • You can link your CancellationToken to another, so that when one is cancelled another can be considered as cancelled.
  • By Task if you mean System.Threading.Tasks.Task a volatile boolean cannot transition the state of the Task to cancelled but CancellationToken can.
like image 165
Sriram Sakthivel Avatar answered Oct 21 '22 20:10

Sriram Sakthivel