Archive

Archive for September 11th, 2019

What happens when you throw an exception in Parallel Loops

September 11th, 2019 Comments off

Bad things, bad things happen … explosions, tears … and maybe more

In the example above, the code will explode because of the exception.
So obviously we will add a try catch block…

And that will work, (of course)

But what if we want to run an async function in parallel … then what do we do?

In the case above you fire tasks, but don’t really wait for them to complete.
The async and await might give you the feeling that you are doing something truly in parallel … but you are not
Because Parallel.ForEach has no overload accepting a Func<Task>, it accepts only Action delegates.

The easy way out is to use Task as they were intended

Now obviously this is ugly code, but you get the idea … run all the tasks in parallel and wait for them all to finish.

Once they are all done, you can throw an aggregation of errors…. if there are any

Have a look at the code on my github page for more information/sample