简体   繁体   English

并行运行多个任务。 如何获取TaskCancelledException背后的原因?

[英]Running multiple tasks in parallel. How to get the reason behind a TaskCancelledException?

Here is my code: 这是我的代码:

            foreach (var batch in listOfBatches)
            {
                var baseTask = Task.Run(() => GetResult(batch));

                backgroundTasks.Add(baseTask);
            }

            var combinedTask = Task.WhenAll(backgroundTasks);
            var selections = combinedTask.ContinueWith(task => task.Result.SelectMany(x => x).ToList(),
                TaskContinuationOptions.OnlyOnRanToCompletion);

            return selections.Result;

GetResult would sometimes throw an exception for one of the batches. GetResult有时会为其中一个批次抛出异常。 In this case, I want the user to see what the actual exception thrown by GetResult is. 在这种情况下,我希望用户查看GetResult抛出的实际异常是什么。 However, the output isn't the actual exception, but rather, a TaskCancelledException. 但是,输出不是实际的异常,而是TaskCancelledException。 How do I extract the exception thrown by GetResult so that the user can see it? 如何提取GetResult引发的异常,以便用户可以看到它?

Don't use ContinueWith to add continuations to tasks. 不要使用ContinueWith向任务添加延续。 Use await . 使用await Among other things, it has much more intuitive error handling semantics. 除其他外,它具有更加直观的错误处理语义。 If you await the task returned by WhenAll , the current method's task will be marked as faulted and represent the first error in the tasks you passed to WhenAll . 如果您await WhenAll返回的任务,则当前方法的任务将被标记为有故障,并且表示传递给WhenAll的任务中的第一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM