带有取消支持的 Task.Run [英] Task.Run with cancellation support

查看:51
本文介绍了带有取消支持的 Task.Run的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个Task.Run 示例.它展示了如何创建具有取消支持的任务.

Consider this Task.Run example. It shows how to create a task with cancellation support.

我正在做类似的事情:

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

我的问题:

  1. 既然我已经有了对取消令牌的引用,为什么要将它作为参数传递给 Task.Run 调用?

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

I often see the following code in examples:

if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();

这段代码的目的是什么?为什么不直接从方法中return?

What's the purpose of this code? Why not just return from the method?

推荐答案

  1. 如果您将取消令牌传递给 Task.Run,如果在 Task 开始之前取消了令牌,它将永远不会开始为您节省资源(我的意思是不创建线程等).

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

如果你只是从方法中返回,任务的状态不会是Canceled,而是RanToCompletion.显然,这不是您所期望的.

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.

或者,您可以使用 CancellationToken 作为参数抛出 OperationCanceledException,这将使 Task.Status 成为 Canceled,但这是一种困难而冗长的方式.token.ThrowIfCancellationRequested 简洁.

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.

您可以简单地使用token.ThrowIfCancellationRequested();,无需检查token.IsCancellationRequested.ThrowIfCancellationRequested 方法已经这样做了.

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

这篇关于带有取消支持的 Task.Run的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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