标签:子线程异常 异常处理 exception thread
一 直接在主线程捕获子线程异常(此方法不可取)
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); } } } }
二 在子线程中捕获并处理异常
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(); } } }
三 子线程中捕获异常,在主线程中处理异常
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); } } } }
此方法的好处是当主线程开启了多个子线程时,可以获取所有子线程的异常后再一起处理。
标签:子线程异常 异常处理 exception thread
原文地址:http://blog.csdn.net/yl2isoft/article/details/46574965