Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Created March 8, 2017 14:20
Show Gist options
  • Save miteshsureja/f58cc20cf59a57c225c4615d427c6822 to your computer and use it in GitHub Desktop.
Save miteshsureja/f58cc20cf59a57c225c4615d427c6822 to your computer and use it in GitHub Desktop.
How to handle exception in Parallel.For and Parallel.Foreach loop? – Task Parallel Library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace ParallelFor
{
class Program
{
static void Main(string[] args)
{
try
{
DoSomeWork();
}
catch (AggregateException ex)
{
//loop through all the exception
foreach(Exception e in ex.InnerExceptions)
{
if (e is ArgumentException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
}
else
throw e;
}
}
Console.ReadLine();
}
public static void DoSomeWork()
{
//ConcurrentQueue allows to queue item from multiple threads.
ConcurrentQueue<Exception> exceptionQueue = new ConcurrentQueue<Exception>();
Parallel.For(0, 100, (i) =>
{
try
{
if (i == 20 || i == 30 || i == 40)
throw new ArgumentException();
Console.Write("{0}, ", i);
}
catch (Exception e)
{
//Adding all the exceptions thrown from multiple thread in queue
exceptionQueue.Enqueue(e);
}
});
//throw all the exception as AggregateException after loop completes
if (exceptionQueue.Count > 0) throw new AggregateException(exceptionQueue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment