Handling exceptions in parallel loops in .NET C#

If a thread in a parallel loop throws an exception then no new iterations will be started. However, iterations already in progress are allowed to run to completion.

You can check if some other iteration has thrown an exception using the the ParallelLoopState class. This class has an IsExceptional property:

Parallel.For(0, 10, (int index, ParallelLoopState state) =>
{
	if (state.IsExceptional)
	{
		//do something
	}
});

All exceptions throw within the parallel loop are collected within an AggregateException object:

List<int> integers = new List<int>();

for (int i = 0; i <= 100; i++)
{
	integers.Add(i);
}

try
{
	Parallel.ForEach(integers, (int item, ParallelLoopState state) =>
	{
		if (item > 50)
		{
			throw new ArgumentNullException("Something has happened");
		}
		else
		{
			Console.WriteLine("Less than 50: {0}", item);
		}

		if (state.IsExceptional)
		{
			Console.WriteLine("Exception!");
		}

	});
}
catch (AggregateException ae)
{
	ae.Handle((inner) =>
	{
		Console.WriteLine(inner.Message);
		return true;
	});
}

You can read more about handling exceptions throw by tasks here, here and here.

Please view the comment section for a link with another example.

View the list of posts on the Task Parallel Library here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Handling exceptions in parallel loops in .NET C#

  1. How about collecting in a blocking collection the exceptions inside the foreach and aggregate? http://msdn.microsoft.com/en-us/library/dd460695(v=vs.110).aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: