TPL - Handle exception

Scenario:

Process data in parallel and handle exception for each thread and then send them back to the caller as AggregateException.

Solution:

MSDN: Handle all exception generated by each thread by wrapping all exceptions from the loop in a System.AggregateException.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    public class ParallelAggregateExceptions
        {
            static void Main(string[] args)
            {
                int[] count = Enumerable.Range(0, 50).ToArray();
    
                try
                {
                    ProcessData(count);
                }
                catch (AggregateException ae)
                {
                    var ignoredExceptions = new List<Exception>();
    
                    foreach (var ex in ae.Flatten().InnerExceptions)
                    {
                        if (ex is ArgumentException)
                            Console.WriteLine(ex.Message);
                        else
                            ignoredExceptions.Add(ex);
                    }
    
                    if (ignoredExceptions.Count > 0)
                    {
                        throw new AggregateException(ignoredExceptions);
                    }
                }
    
                Console.ReadLine();
            }
    
            private static void ProcessData(int[] count)
            {
                //store exceptions in thread safe way
                var exceptions = new ConcurrentQueue<Exception>();
    
                Parallel.ForEach(count, c =>
                {
                    try
                    {
                        if (c < 5)
                            throw new ArgumentException($"Value {c}, is less than 5.");
                        else
                            Console.Write(c + " ");
                    }
                    // Store exception and continue
                    catch (Exception e)
                    {
                        exceptions.Enqueue(e);
                    }
                });
    
                //Console.WriteLine();
    
                // Throw the exceptions here after the loop completes.
                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...