简体   繁体   中英

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. In this case, I want the user to see what the actual exception thrown by GetResult is. However, the output isn't the actual exception, but rather, a TaskCancelledException. How do I extract the exception thrown by GetResult so that the user can see it?

Don't use ContinueWith to add continuations to tasks. Use 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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