ThrowIfCancellationRequested似乎没有引发任何异常 [英] ThrowIfCancellationRequested doesn't seem to throw any exceptions
问题描述
我有以下代码:
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:
- 调用
Compute()
方法 - 等待直到完成
- 写关于完成的控制台
- 检查是否请求取消,并抛出
OperationCanceledException
.
- Calls
Compute()
method - Waits until its completion
- Writes to console about finish
- 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屋!