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++)

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

		if (state.IsExceptional)

catch (AggregateException ae)
	ae.Handle((inner) =>
		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.

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 to Adi Bilauca (@abilauca) Cancel 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s


A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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: