如何捕获子线程异常

来源:互联网 发布:poe网络监控安装教程 编辑:程序博客网 时间:2024/05/16 15:27

一 直接在主线程捕获子线程异常(此方法不可取)

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);            }        }    }}


使用此方法同样可以成功捕获并处理子线程异常,程序同样不会崩溃。

此方法的好处是当主线程开启了多个子线程时,可以获取所有子线程的异常后再一起处理。

 

 

 

1 0
原创粉丝点击