多线程之异常处理
using System; using System.Threading; namespace Chapter1.Recipe11 { class Program { static void Main(string[] args) { var t = new Thread(FaultyThread); t.Start(); //异常被捕获到 t.Join(); try { t = new Thread(BadFaultyThread); t.Start(); } catch (Exception ex) //应用程序并不会在这里捕获线程的异常,而是会直接退出 { Console.WriteLine("We won't get here!"); } Console.ReadKey(); } static void BadFaultyThread() { Console.WriteLine("Starting a faulty thread..."); Thread.Sleep(TimeSpan.FromSeconds(2)); throw new Exception("Boom!"); } static void FaultyThread() { try { Console.WriteLine("Starting a faulty thread..."); Thread.Sleep(TimeSpan.FromSeconds(1)); throw new Exception("Boom!"); } catch (Exception ex) { Console.WriteLine("Exception handled: {0}", ex.Message); } } } }
在线程中始终使用try...catch代码块捕获异常是非常重要的,因为这不可能在线程代码之外来捕获异常。原则上说,每个线程的业务异常应该在自己的内部处理完毕。
参考: