CancellationTokenSource vs. volatile boolean

前端 未结 1 1113
礼貌的吻别
礼貌的吻别 2021-01-01 12:05

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

相关标签:
1条回答
  • 2021-01-01 12:12

    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.
    0 讨论(0)
提交回复
热议问题