【发布时间】:2012-04-18 00:48:44
【问题描述】:
我正在使用任务并行库来设置如下所示的任务链,但我得到了一种奇怪的异常处理体验,我不明白。
我使用 Parallel.ForEach 并调用包含对以下方法的调用的 Action。此 Parallel.ForEach 包含在 try...catch(AggregateException) 中,当发生异常时 - 就像在其中一个 Parallel 分支中一样 - SchemaValidation 异常,然后我希望在 AggregateException 中看到它。
但是,我得到的是“任务已取消”-TaskCanceledException。我的 SchemaValidationException 到哪里去了?
private static void ProcessChunk(Task<ISelectedChunk> selectionTask,
IRepository repository,
IIdentifiedExtractChunk identifiedExtractChunk,
IBatchRunConfiguration batchRunConfiguration,
IBatchRun batchRun,
ILog log,
IAuthenticationCertificate authenticationCertificate,
IFileSystem fileSystem,
long batchRunRid)
{
var transformationTask = selectionTask.ContinueWith(TransformationFunction.Transformation(identifiedExtractChunk, batchRunConfiguration, batchRun),
TaskContinuationOptions.NotOnFaulted);
var schemaValidationTask = transformationTask.ContinueWith(SchemaValidationFunction.SchemaValidationTask(batchRunConfiguration),
TaskContinuationOptions.NotOnFaulted);
var compressTask = schemaValidationTask.ContinueWith(CompressFunction.CompressTask(identifiedExtractChunk),
TaskContinuationOptions.NotOnFaulted);
var encryptTask = compressTask.ContinueWith(EncryptionFunction.EncryptTask(authenticationCertificate),
TaskContinuationOptions.NotOnFaulted);
var fileGenerationTask = encryptTask.ContinueWith(FileGenerationFunction.FileGenerationTask(identifiedExtractChunk, batchRunConfiguration, fileSystem),
TaskContinuationOptions.NotOnFaulted);
// Take the time before we start the processing
DateTime startBatchItemProcessing = DateTime.Now;
// Start with the Selection Task
selectionTask.Start();
// And wait on the last task in the chain
fileGenerationTask.Wait();
// Take the time at the end of the processing
DateTime endBatchItemProcessing = DateTime.Now;
// Record all the relevant information and add it to the collection
IBatchChunkProcessed batchChunkProcessed = GetBatchItemProcessed(identifiedExtractChunk, batchRunRid, fileGenerationTask.Result, transformationTask.Result.Item2, startBatchItemProcessing, endBatchItemProcessing);
BatchItemsProcessed.Add(batchChunkProcessed);
【问题讨论】:
-
你为什么还要在这里使用
Tasks?为什么不按顺序执行所有方法? -
代码似乎与问题无关。贴出捕获并处理异常的代码。
-
@svick - 传入的选择任务是并行的。此外,这些是离散的构建块任务,可以很容易地在其他环境中重复使用 - 并可能成为根任务。
-
@HansPassant - 问题不在于异常处理代码 - 无论我把它放在哪里,我都遇到了同样的问题。
标签: c# .net exception task-parallel-library