Archive

Archive for September, 2019

Parallel.ForEach Async in C#

September 13th, 2019 Comments off

As mentioned in my previous post, to get a ‘proper’ parallel foreach that is async is a bit of a pain

So the solution is to write a true async function

And you can call it …

Of course, you can refine it by adding check for tokens that cannot be cancelled as well as empty sources

First prize you must make sure that the body of the ForEach takes in the token and cancels cleanly otherwise this will jump out with thread left up in the air… but at least it will get out.

Edit: As someone pointed out to me on StackOverflow there are a couple of subtle ways I can improve my implementation … so I added them here

Categories: development Tags: , , ,

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