I have a problem with exception handling and parallel tasks.
The code shown below starts 2 tasks and waits for them to finish. My problem is, that in case a task throws an exception, the catch handler is never reached.
List<Task> tasks = new List<Task>();
try
{
tasks.Add(Task.Factory.StartNew(TaskMethod1));
tasks.Add(Task.Factory.StartNew(TaskMethod2));
var arr = tasks.ToArray();
Task.WaitAll(arr);
}
catch (AggregateException e)
{
// do something
}
However when I use the following code to wait for the tasks with a timeout, the exception is caught.
while(!Task.WaitAll(arr,100));
I seem to be missing something, as the documentation for WaitAll
describes my first attempt to be the correct one. Please help me in understanding why it is not working.
Can't reproduce this - it works fine for me:
That prints "Something went wrong" just as I'd expect.
Is it possible that one of your tasks isn't finished?
WaitAll
really does wait for all the tasks to complete, even if some have already failed.Here's how I solved the problem, as alluded to in the comments on my answer/question (above):
The caller catches any exceptions raised by the tasks being coordinated by the barrier, and signals the other tasks with a forced cancellation:
I was trying to create a call for each item in a collection, which turned out something like this:
I had to add the Thread.Sleep after each addition of a child task because if I didn't, the process would tend to overwrite the currAcctNo with the next iteration. I would have 3 or 4 distinct account numbers in my list, and when it processed each, the ProcessThisAccount call would show the last account number for all calls. Once I put the Sleep in, the process works great.