閱讀英文

共用方式為


AggregateException.Flatten 方法

定義

AggregateException 執行個體簡維成單一新執行個體。

public AggregateException Flatten ();

傳回

新的扁平化 AggregateException

範例

下例中,巢狀 AggregateException 執行個體被扁平化,並只在一個迴圈中處理。

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.

您也可以使用 AggregateException.Flatten 方法,從被單一 AggregateException 執行個體之多個工作擲回的多個 AggregateException 執行個體中,重新擲回內部的例外狀況,如下例所示。

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public class Example2
{
   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.

備註

如果工作有擲回例外狀況的附加子工作,該例外狀況會先包裝在例外狀況中 AggregateException ,再傳播至父工作,它會將該例外狀況包裝在自己的 AggregateException 例外狀況中,再將其傳播回呼叫執行緒。 在這種情況下, InnerExceptionsWaitTask.WaitAnyTask.WaitAll 方法攔截到的 AggregateException 例外 Task.Wait 狀況屬性包含一或多個 AggregateException 實例,而不是造成錯誤的原始例外狀況。 若要避免重複巢狀 AggregateException 例外狀況,您可以使用 Flatten 方法來移除所有巢狀 AggregateException 例外狀況,讓 InnerExceptionsAggregateException 回物件的 屬性包含原始例外狀況。

這個方法會遞迴扁平化目前 AggregateException 實例 AggregateException 內部例外狀況的所有例外狀況實例。 新 AggregateException 中傳回的內部例外狀況是來自目前 AggregateException 實例根目錄之例外狀況樹狀結構中所有內部例外狀況的聯集。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另請參閱