AggregateException.Flatten 메서드

정의

AggregateException 인스턴스를 단일 새 인스턴스로 평면화합니다.Flattens an AggregateException instances into a single, new instance.

public:
 AggregateException ^ Flatten();
public AggregateException Flatten ();
member this.Flatten : unit -> AggregateException
Public Function Flatten () As AggregateException

반환

평면화된 새 AggregateException입니다.A new, flattened AggregateException.

예제

다음 예제에서는 중첩된 AggregateException 인스턴스가 하나의 루프에서 결합되고 처리됩니다.In the following example, nested AggregateException instances are flattened and handled in just one loop.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var task1 = Task.Factory.StartNew(() => {
                     var child1 = Task.Factory.StartNew(() => {
                        var child2 = Task.Factory.StartNew(() => {
                            // This exception is nested inside three AggregateExceptions.
                            throw new CustomException("Attached child2 faulted.");
                        }, TaskCreationOptions.AttachedToParent);

                        // This exception is nested inside two AggregateExceptions.
                        throw new CustomException("Attached child1 faulted.");
                     }, TaskCreationOptions.AttachedToParent);
      });

      try {
         task1.Wait();
      }
      catch (AggregateException ae) {
         foreach (var e in ae.Flatten().InnerExceptions) {
            if (e is CustomException) {
               Console.WriteLine(e.Message);
            }
            else {
               throw;
            }
         }
      }
   }
}

public class CustomException : Exception
{
   public CustomException(String message) : base(message)
   {}
}
// The example displays the following output:
//    Attached child1 faulted.
//    Attached child2 faulted.
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim task1 = Task.Factory.StartNew(Sub()
                                           Dim child1 = Task.Factory.StartNew(Sub()
                                                                                 Dim child2 = Task.Factory.StartNew(Sub()
                                                                                                                       Throw New CustomException("Attached child2 faulted.")
                                                                                                                    End Sub,
                                                                                                                    TaskCreationOptions.AttachedToParent)
                                                                                                                    Throw New CustomException("Attached child1 faulted.")
                                                                              End Sub,
                                                                              TaskCreationOptions.AttachedToParent)
                                        End Sub)

      Try
         task1.Wait()
      Catch ae As AggregateException
         For Each ex In ae.Flatten().InnerExceptions
            If TypeOf ex Is CustomException Then
               Console.WriteLine(ex.Message)
            Else
               Throw
            End If
         Next
      End Try
   End Sub
End Module

Class CustomException : Inherits Exception
   Public Sub New(s As String)
      MyBase.New(s)
   End Sub
End Class
' The example displays the following output:
'       Attached child1 faulted.
'       Attached child2 faulted.

또한 다음 예제가 보여주는 것처럼 AggregateException.Flatten 메서드를 사용하여 단일 AggregateException 인스턴스에서 여러 작업에 의해 throw된 여러 AggregateException 인스턴스의 내부 예외를 다시 throw할 수 있습니다.You can also use the AggregateException.Flatten method to rethrow the inner exceptions from multiple AggregateException instances thrown by multiple tasks in a single AggregateException instance, as the following example shows.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class Example
{
   public static void Main()
   {
        try {
            ExecuteTasks();
        }
        catch (AggregateException ae) {
            foreach (var e in ae.InnerExceptions) {
                Console.WriteLine("{0}:\n   {1}", e.GetType().Name, e.Message);
            }
        }
   }

   static void ExecuteTasks()
   {
        // Assume this is a user-entered String.
        String path = @"C:\";
        List<Task> tasks = new List<Task>();

        tasks.Add(Task.Run(() => {
                             // This should throw an UnauthorizedAccessException.
                              return Directory.GetFiles(path, "*.txt",
                                                        SearchOption.AllDirectories);
                           }));

        tasks.Add(Task.Run(() => {
                              if (path == @"C:\")
                                 throw new ArgumentException("The system root is not a valid path.");
                              return new String[] { ".txt", ".dll", ".exe", ".bin", ".dat" };
                           }));

        tasks.Add(Task.Run(() => {
                               throw new NotImplementedException("This operation has not been implemented.");
                           }));

        try {
            Task.WaitAll(tasks.ToArray());
        }
        catch (AggregateException ae) {
            throw ae.Flatten();
        }
    }
}
// The example displays the following output:
//       UnauthorizedAccessException:
//          Access to the path 'C:\Documents and Settings' is denied.
//       ArgumentException:
//          The system root is not a valid path.
//       NotImplementedException:
//          This operation has not been implemented.
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
       Try
          ExecuteTasks()
       Catch ae As AggregateException
          For Each e In ae.InnerExceptions
             Console.WriteLine("{0}:{2}   {1}", e.GetType().Name, e.Message,
                               vbCrLf)
          Next
       End Try
    End Sub

    Sub ExecuteTasks()
        ' Assume this is a user-entered String.
        Dim path = "C:\"
        Dim tasks As New List(Of Task)
        
        tasks.Add(Task.Run(Function()
                             ' This should throw an UnauthorizedAccessException.
                              Return Directory.GetFiles(path, "*.txt",
                                                        SearchOption.AllDirectories)
                           End Function))

        tasks.Add(Task.Run(Function()
                              If path = "C:\" Then
                                 Throw New ArgumentException("The system root is not a valid path.")
                              End If
                              Return { ".txt", ".dll", ".exe", ".bin", ".dat" }
                           End Function))

        tasks.Add(Task.Run(Sub()
                              Throw New NotImplementedException("This operation has not been implemented.")
                           End Sub))

        Try
            Task.WaitAll(tasks.ToArray)
        Catch ae As AggregateException
            Throw ae.Flatten()
        End Try
    End Sub
End Module
' The example displays the following output:
'       UnauthorizedAccessException:
'          Access to the path 'C:\Documents and Settings' is denied.
'       ArgumentException:
'          The system root is not a valid path.
'       NotImplementedException:
'          This operation has not been implemented.

설명

작업에 예외를 throw 하는 연결 된 자식 작업이 있는 경우 해당 예외는 부모 작업으로 전파 되기 전에 AggregateException 예외에 래핑됩니다. 그러면 해당 예외는 해당 예외를 자체 AggregateException 예외로 래핑하고 호출 스레드로 다시 전파 합니다.If a task has an attached child task that throws an exception, that exception is wrapped in an AggregateException exception before it is propagated to the parent task, which wraps that exception in its own AggregateException exception before it propagates it back to the calling thread. 이러한 경우 Task.Wait, Wait, Task.WaitAny 또는 Task.WaitAll 메서드에 의해 catch 된 AggregateException 예외의 InnerExceptions 속성은 오류를 발생 시킨 원래 예외가 아니라 하나 이상의 AggregateException 인스턴스를 포함 합니다.In such cases, the InnerExceptions property of the AggregateException exception that is caught by the Task.Wait, Wait, Task.WaitAny or Task.WaitAll method contains one or more AggregateException instances, not the original exceptions that caused the fault. 중첩 된 AggregateException 예외를 반복할 필요가 없도록 Flatten 메서드를 사용 하 여 중첩 된 모든 AggregateException 예외를 제거할 수 있습니다. 그러면 반환 된 AggregateException 개체의 InnerExceptions 속성에 원래 예외가 포함 됩니다.To avoid having to iterate over nested AggregateException exceptions, you can use the Flatten method to remove all the nested AggregateException exceptions, so that the InnerExceptions property of the returned AggregateException object contains the original exceptions.

이 메서드는 현재 AggregateException 인스턴스의 내부 예외인 AggregateException 예외의 모든 인스턴스를 재귀적으로 평면화 합니다.This method recursively flattens all instances of AggregateException exceptions that are inner exceptions of the current AggregateException instance . AggregateException에서 반환 되는 내부 예외는 현재 AggregateException 인스턴스를 기반으로 하는 예외 트리의 모든 내부 예외를 결합 한 것입니다.The inner exceptions returned in the new AggregateException are the union of all the inner exceptions from exception tree rooted at the current AggregateException instance.

적용 대상

추가 정보