一 直接在主線程捕獲子線程異常(此方法不可?。?/strong>
- using System;
- using System.Threading;
- namespace CatchThreadException
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- Thread t = new Thread(() =>
- {
- throw new Exception("我是子線程中拋出的異常,!");
- });
- t.Start();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- }
代碼執(zhí)行結(jié)果顯示存在“未經(jīng)處理的異?!?。所以使用此方法并不能捕獲子線程拋出的異常。
二 在子線程中捕獲并處理異常
- using System;
- using System.Threading;
- namespace CatchThreadException
- {
- class Program
- {
- static void Main(string[] args)
- {
- Thread t = new Thread(() =>
- {
- try
- {
- throw new Exception("我是子線程中拋出的異常!");
- }
- catch (Exception ex)
- {
- Console.WriteLine("子線程:" +
- ex.Message);
- }
- });
- t.Start();
- }
- }
- }
使用此方法可以成功捕獲并處理子線程異常,,程序不會(huì)崩潰,。
三 子線程中捕獲異常,在主線程中處理異常
- using System;
- using System.Threading;
- namespace CatchThreadException
- {
- class Program
- {
- private delegate void ThreadExceptionEventHandler(Exception ex);
- private static ThreadExceptionEventHandler exceptionHappened;
- private static Exception exceptions;
- static void Main(string[] args)
- {
- exceptionHappened = new ThreadExceptionEventHandler(ShowThreadException);
- Thread t = new Thread(() =>
- {
- try
- {
- throw new Exception("我是子線程中拋出的異常,!");
- }
- catch (Exception ex)
- {
- OnThreadExceptionHappened(ex);
- }
- }
- );
- t.Start();
- t.Join();
- if (exceptions != null)
- {
- Console.WriteLine(exceptions.Message);
- }
- }
- private static void ShowThreadException(Exception ex)
- {
- exceptions = ex;
- }
- private static void OnThreadExceptionHappened(Exception ex)
- {
- if (exceptionHappened != null)
- {
- exceptionHappened(ex);
- }
- }
- }
- }
使用此方法同樣可以成功捕獲并處理子線程異常,,程序同樣不會(huì)崩潰。
此方法的好處是當(dāng)主線程開(kāi)啟了多個(gè)子線程時(shí),,可以獲取所有子線程的異常后再一起處理。
|