处理方法:线程启动后,使用try-catch,通过wait或者waitall来捕获异常。
单个Task的情况:
System.Threading.Tasks.Task task1 = new System.Threading.Tasks.Task(TaskMethod);
task1.Start();
try
{
task1.Wait();
}
catch(AggregateException ae)
{
Console.WriteLine("task1 异常");
}
多个Task的情况:
System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[];
tasks[] = new System.Threading.Tasks.Task(TaskMethod);
tasks[].Start();
tasks[] = new System.Threading.Tasks.Task(TaskMethod);
tasks[].Start();
tasks[] = new System.Threading.Tasks.Task(TaskMethod);
tasks[].Start();
try
{
System.Threading.Tasks.Task.WaitAll(tasks);
}
catch(AggregateException ex)
{
foreach (var exception in ex.InnerExceptions)
{
Console.WriteLine(exception.ToString());
}
}
public static void TaskMethod()
{
//略
}