locked
Error handling for every iteration with Parallel class RRS feed

  • Question

  • User1904516115 posted

    How to handle exception with Parallel class for every iteration? I am using following code but "Handled" message is printing only 5 times

    using System;
    using System.Threading.Tasks;
    
    namespace ThreadPooling
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    Parallel.For(1, 10, i =>
                    {
                        int dividend = 0;
                        int result = i / dividend;
                    });
                }
                catch (AggregateException ex)
                {
                    ex.Flatten().Handle(p =>
                    {
                        Console.WriteLine("Handled");
                        return true;
                    });
    
                }
                Console.ReadLine();
            }
        }
    }
    

    Monday, February 5, 2018 7:31 PM

All replies

  • User475983607 posted

    See the docs

    https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-handle-exceptions-in-parallel-loops

        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    ProcessDataInParallel();
                }
                catch (AggregateException ae)
                {
                    // This is where you can choose which exceptions to handle.
                    foreach (var ex in ae.InnerExceptions)
                    {
                        if (ex is DivideByZeroException)
                            Console.WriteLine(ex.Message);
                        else
                            throw ex;
                    }
    
                }
    
                Console.ReadLine();
            }
    
            private static void ProcessDataInParallel()
            {
                // Use ConcurrentQueue to enable safe enqueueing from multiple threads.
                var exceptions = new ConcurrentQueue<Exception>();
    
                // Execute the complete loop and capture all exceptions.
                Parallel.For(1, 10, i =>
                {
                    try
                    {
                        int dividend = 0;
                        int result = i / dividend;
                    }
                    // Store the exception and continue with the loop.                    
                    catch (Exception e) { exceptions.Enqueue(e); }
                });
    
                // Throw the exceptions here after the loop completes.
                if (exceptions.Count > 0) throw new AggregateException("DivideByZero", exceptions);
    
            }
        }

    Monday, February 5, 2018 7:43 PM