本文整理汇总了C#中System.AggregateException.Flatten方法的典型用法代码示例。如果您正苦于以下问题:C# AggregateException.Flatten方法的具体用法?C# AggregateException.Flatten怎么用?C# AggregateException.Flatten使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.AggregateException
的用法示例。
在下文中一共展示了AggregateException.Flatten方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
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)
{}
}
输出:
Attached child1 faulted. Attached child2 faulted.
示例2: Main
//引入命名空间
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();
}
}
}
输出:
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.