using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static void Main(string [] args)
{
#region Thread里的运行方法如果有异常没有处理会导致控制台程序异常终止
//var thread1 = new Thread(() => TaskMethod("thread1"));
//thread1.Start();
//// 这里try-catch捕获不到异常
//try
//{
// var thread2 = new Thread(() => TaskMethod("thread2"));
// thread2.Start();
//}
//catch(Exception ex)
//{
// Console.WriteLine("{0} 异常,异常信息:{1}", "thread2", ex.Message);
//}
#endregion
#region Task里的运行方法如果有异常但是调用线程如果不去获取任务Task.Result值就不会把task里的异常传播到调用线程,就不会导致控制台程序异常终止
//var task1 = Task.Run(() => TaskMethod("task1"));
//// 这里使用try-catch捕获不到Task里的异常,因为task里的异常没有传播过来
//try
//{
// var task2 = Task.Run(() => TaskMethod("task2"));
//}
//catch(Exception ex)
//{
// Console.WriteLine("{0} 异常,异常信息:{1}", "task2", ex.Message);
//}
#endregion
#region Task里的运行方法有异常,调用线程获取task的Result值会把异常传播给调用线程
//var task3 = Task.Run(() => TaskMethod("task3"));
//var task4 = Task.Run(() => TaskMethod("task4"));
//// 这里获取task3的任务结果Result,会把异常传播过来
//// tyr-catch可以捕获到异常
//try
//{
// var task3Res = task3.Result;
//}
//catch(Exception ex)
//{
// // 输出: "task3 异常,异常信息:One or more errors occurred. (task3 boom)"
// Console.WriteLine("{0} 异常,异常信息:{1}", "task3", ex.Message);
//}
//// 这里获取task3、task4的结果
//// try-catch可以捕获到异常
//try
//{
// var results = Task.WhenAll(task3, task4).Result;
//}
//catch(Exception ex)
//{
// // 输出:"task3,4 异常,异常信息:One or more errors occurred. (task3 boom) (task4 boom)"
// Console.WriteLine("{0} 异常,异常信息:{1}", "task3,4", ex.Message);
//}
#endregion
#region async/await的异步任务里当主调线程使用await等待任务结果时会把异常传播给主调线程
var t1 = AsyncTest("AsyncTask1");
try
{
//var t2 = AsyncTest("AsyncTask2"); // try-catch 不能捕获到异常
var t2 = AsyncTest("AsyncTask2").Result; // try-catch 能捕获到异常,因为 .Result
}
catch(Exception ex)
{
// 输出:"AsyncTask2 发生异常,异常信息:One or more errors occurred. (AsyncTask2 boom)"
Console.WriteLine("{0} 发生异常,异常信息:{1}", "AsyncTask2", ex.Message);
}
#endregion
Console.WriteLine("Main ok");
Console.ReadLine();
}
public async static Task<string> AsyncTest(string taskName)
{
// 由于有await,try-catch可以捕获异常
try
{
var resStr = await Task.Run(() => TaskMethod(taskName));
return resStr; // 这里无法执行,因为 await等待的方法有异常
}
catch(Exception ex)
{
// 输出: "AsyncTask1 发生异常,异常信息:AsyncTask1 boom"
Console.WriteLine("{0} 发生异常,异常信息:{1}", taskName, ex.Message);
}
var resStr1 = await Task.Run(() => TaskMethod(taskName));
return resStr1; // 这里无法执行,因为 await等待的方法有异常
}
public static string TaskMethod(string taskName)
{
Thread.Sleep(1000);
Console.WriteLine("{0} running ", taskName);
throw new Exception(string.Format("{0} boom", taskName));
return taskName + " ok";
}
}