如果并行任务抛出异常则取消任务 [英] Canceling task if a parallel task throw an exception
问题描述
我有两个共享相同取消令牌的并行任务,客户端要求两个结果列表,例如:
I have two parallel tasks that share the same cancellation token, the client asks for two lists of result like:
class ResponseDTO
{
public IEnumerable<Entity1> Entity1List { get; set; }
public IEnumerable<Entity2> Entity2List { get; set; }
}
这两个请求是同时计算和依赖的,因此如果列表中的一个没有结果,则无需等待另一个结果.
The two requests are calculated simultaneously and depended, so if one of the list is has no result there no need to wait for the other result.
var cts = new CancellationTokenSource();
var token = cts.Token;
Task task1 = new Task(() =>
{
//fetch Entity1 results into entity1List
if (!entity1List.Any())
{
cts.Cancel();
}
else
{
responseDTO.Entity1List = entity1List;
}
}, token);
Task task2 = new Task(() =>
{
//fetch Entity2 results into entity2List
if (!entity2List.Any())
{
cts.Cancel();
}
else
{
responseDTO.Entity2List = entity2List;
}
}, token);
task1.Start();
task2.Start();
try
{
Task.WaitAll(new[] { task1, task2 }, token);
}
catch (OperationCanceledException oce)
{
return responseDTO;
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
//Log the exception
return responseDTO;
}
return responseDTO;
如果任务返回空列表,取消工作正常.
In case of the tasks has returned an empty list the canceling works fine.
我的问题是:如果另一个任务抛出一般异常,如何取消其中一个任务?
My question is: how to cancel one of the tasks if the other one threw a general exception?
推荐答案
已通过 @noobed 评论解决.
Solved with @noobed comment.
try
{
//fetch Entity1 results into entity1List
}
catch
{
cts.Cancel();
}
在一般异常的情况下,它会被catch,并且可以使用cancel调用cts.
In case of general exception it will be catch, and the cts can be called with cancel.
这篇关于如果并行任务抛出异常则取消任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!