Search code examples
c#taskvolatilecancellationtokensource

CancellationTokenSource vs. volatile boolean


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


Solution

  • 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.