CancellationTokenSource vs. volatile boolean

送分小仙女□ 提交于 2019-11-29 16:58:16

问题


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


回答1:


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.


来源:https://stackoverflow.com/questions/30024969/cancellationtokensource-vs-volatile-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!