任务。取消支持
考虑 this task> task.run 示例
。它显示了如何通过取消支持创建任务。
我正在做类似的事情:
Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token);
我的问题:
,因为我已经提到了取消令牌,为什么将其作为参数作为参数的目的。
我经常在示例中看到以下代码:
if(token.isCellationRequested)token.throwifcancellationRequelQulationRequequeldeRequrequreDeRequested();
此代码的目的是什么?为什么不只是返回
该方法呢?
Consider this Task.Run
example. It shows how to create a task with cancellation support.
I am doing something similar:
Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token);
My questions:
Since I already have a reference to the cancellation token, why the purpose of passing it as a parameter to the
Task.Run
invocation?I often see the following code in examples:
if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
What's the purpose of this code? Why not just return
from the method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将取消令牌传递给
task.run
,如果在启动任务之前已取消令牌,它将永远不会开始为您节省资源(我的意思是不要创建线程等)。如果您只是从方法返回,任务的状态将不会为
取消
,它将是rantococtertion
。显然,这不是您期望的。另外,您可以将
operationCanceLedException
用concellationToken
作为参数,这将使task.status.status
be取消
,,但这是艰难而冗长的方式。token.throwifcancellationRequested
是简洁的。您只需使用
token.throwifcancellationRequested();
,无需检查token.iscancellationRequested
即可。throwCancellationRequested
方法已经这样做。If you pass the cancellation token to
Task.Run
, if the token is cancelled before the Task is started, it will never be started saving you resources(I mean by not creating threads etc).If you just return from the method, the Task's Status will not be
Canceled
, it will beRanToCompletion
. Clearly this isn't what you'll expect.Alternatively you could throw
OperationCanceledException
with theCancellationToken
as parameter, that will make theTask.Status
to beCanceled
, but this is the hard and verbose way.token.ThrowIfCancellationRequested
is concise.You could simply use
token.ThrowIfCancellationRequested();
, no need to check fortoken.IsCancellationRequested
.ThrowIfCancellationRequested
method already does this.