ThrowIfCancellationRequested似乎没有引发任何异常 [英] ThrowIfCancellationRequested doesn't seem to throw any exceptions

查看:487
本文介绍了ThrowIfCancellationRequested似乎没有引发任何异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;

Task.Factory.StartNew(() =>
{
     if (Console.ReadKey().KeyChar == 'c')
         cts.Cancel();
     Console.WriteLine("press any key to exit");
});

 Parallel.ForEach(list, po, (algo) =>
 {
      algo.Compute(); // this compute lasts 1 minute  
      Console.WriteLine("this job is finished");       
      po.CancellationToken.ThrowIfCancellationRequested();
 });

list包含少量元素. 当我按'c'时,所有Compute方法都已经启动.

The list contains few elements. All the Compute methods have already been started when I press 'c'.

当我按'c'时,不会引发任何异常.每个Compute方法都将继续执行直到其正常结束.

When I press 'c', no exception is thrown. Each Compute methods continues its execution until its normal end.

当我按下'c'时,我想停止/杀死所有其余的Compute方法.

I would like to stop/kill all the remain Compute methods when I press 'c'.

推荐答案

取消不能那样工作.这不像调用Thread.Abort()立即终止线程.

Cancellation doesn't work like that. It's not like calling Thread.Abort() to terminate thread immediately.

对于序列中的每个元素,您的代码都会执行:

For each element in a sequence your code does:

  1. 调用Compute()方法
  2. 等待直到完成
  3. 写关于完成的控制台
  4. 检查是否请求取消,并抛出OperationCanceledException.
  1. Calls Compute() method
  2. Waits until its completion
  3. Writes to console about finish
  4. Checks if cancellation was requested and throw the OperationCanceledException if it was.

要取消某些任务,您需要将CancellationToken传递给被调用的方法.
也许值得将长时间运行的计算组织为一个周期,并检查是否在每个步骤中都要求取消,以便尽快将其停止.

In order to cancel some task you need to pass the CancellationToken to the called method.
Perhaps, it's worth organizing your long running computations as a cycle and check if cancellation were requested at each step in order to stop it ASAP.

例如,在您的Compute()方法中,您可以执行如下检查:

For example, in your Compute() method you could perform check like this:

private void Compute(CancellationToken ct)
{
    while (true)
    {
       ComputeNextStep();
       ct.ThrowIfCancellationRequested();
    }
}

这篇关于ThrowIfCancellationRequested似乎没有引发任何异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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