任务。取消支持

发布于 2025-02-08 06:14:24 字数 601 浏览 1 评论 0原文

考虑 this task> task.run 示例。它显示了如何通过取消支持创建任务。

我正在做类似的事情:

Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token);

我的问题:

  1. ,因为我已经提到了取消令牌,为什么将其作为参数作为参数的目的。

  2. 我经常在示例中看到以下代码:

    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:

  1. Since I already have a reference to the cancellation token, why the purpose of passing it as a parameter to the Task.Run invocation?

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶视觉 2025-02-15 06:14:24
  1. 如果将取消令牌传递给task.run,如果在启动任务之前已取消令牌,它将永远不会开始为您节省资源(我的意思是不要创建线程等)。

  2. 如果您只是从方法返回,任务的状态将不会为取消,它将是rantococtertion。显然,这不是您期望的。

另外,您可以将operationCanceLedExceptionconcellationToken作为参数,这将使task.status.status be 取消,,但这是艰难而冗长的方式。 token.throwifcancellationRequested是简洁的。

您只需使用token.throwifcancellationRequested();,无需检查token.iscancellationRequested即可。 throwCancellationRequested方法已经这样做。

  1. 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).

  2. If you just return from the method, the Task's Status will not be Canceled, it will be RanToCompletion. Clearly this isn't what you'll expect.

Alternatively you could throw OperationCanceledException with the CancellationToken as parameter, that will make the Task.Status to be Canceled, but this is the hard and verbose way. token.ThrowIfCancellationRequested is concise.

You could simply use token.ThrowIfCancellationRequested();, no need to check for token.IsCancellationRequested. ThrowIfCancellationRequested method already does this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文