2013-01-13 66 views
2

我想運行異步4層嵌套循環並打印所有聚合異常,但未能這樣做。 Followed MS post on how to handle exception in Parallel libraryParallel.ForEach和Aggregate異常

可以得到爲什麼我總是得到隨機數,而它應該打印3^3次?

Console.WriteLine("{0} was on counter\n\n\n",counter); 

class Program 
{ 
    static void Main() 
    { 
     int counter = 1; 

     List<int> numbers = new List<int> {1, 2, 3}; 

     try 
     { 
      ConcurrentQueue<Exception> exceptions = new ConcurrentQueue<Exception>(); 
      Parallel.ForEach(numbers, number1 => 
      { 
       Parallel.ForEach(numbers, number2 => 
       { 
        Parallel.ForEach(numbers, number3 => 
        { 
         Parallel.ForEach(numbers, number4 => 
         { 
          try 
          { 
           throw new Exception(string.Format("number {0} failed on iteration {1}",number4,counter++)); 
          } 
          catch (Exception exception) 
          { 
           exceptions.Enqueue(exception); 
          } 

         }); 
        }); 
       }); 
      }); 
      if (!exceptions.IsEmpty) 
      { 
       throw new AggregateException(exceptions); 
      } 
     } 
     catch (Exception exception) 
     { 
      Console.WriteLine("{0} was on counter\n\n\n",counter); 
      GetInnerException(exception); 
     } 

     Console.WriteLine("Press any key to exit."); 
     Console.ReadKey(); 
    } 

    public static void GetInnerException(Exception exception) 
    { 
     if (exception.GetType().Equals(typeof(AggregateException))) 
     { 
      AggregateException aggregateException = (AggregateException)exception; 
      foreach (Exception innerException in aggregateException.InnerExceptions) 
      { 
       GetInnerException(innerException); 
      } 
     } 
     else 
     { 
      Console.WriteLine(exception.ToString()); 
     } 
    } 
} 

感謝

回答

6

counter變量不是線程安全的方式遞增。

由於TPL循環將並行運行,因此您的計數器變量將從多個線程遞增。隨着遞增的整型變量是不是原子,你需要通過使用鎖或Interlocked.Increment,使這部分線程安全的,例如:揮發性不需要

throw new Exception(string.Format("number {0} failed on iteration {1}", 
            number4, 
            Interlocked.Increment(ref counter))); 
+3

。 – usr

+0

哎呀 - 壞習慣:-) – tjdecke