CancellationTokenSource与volatile布尔值 [英] CancellationTokenSource vs. volatile boolean

查看:111
本文介绍了CancellationTokenSource与volatile布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用volatile 布尔字段中,通过noa 任务完成吗?

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

推荐答案

当然可以。有许多。我将列出一些。

Of course yes. There are many. I'll list few.


  • CancellationToken 支持回调。当请求取消时,您会收到通知。

  • CancellationToken 支持 WaitHandle

  • 您可以使用 CancellationTokenSource安排取消 CancellationToken .CancelAfter 方法。

  • 您可以将您的 CancellationToken 链接到另一个,这样当一个取消时,另一个可以视为已取消。

  • 通过 Task 表示 System.Threading.Tasks.Task 布尔变量不能将任务的状态转换为已取消,但是 CancellationToken 可以。

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

这篇关于CancellationTokenSource与volatile布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆