Created
March 8, 2017 14:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
How to handle exception in Parallel.For and Parallel.Foreach loop? – Task Parallel Library