多线程之异常处理 编写高质量代码改善C#程序的157个建议——建议66:正确捕获多线程中的异常

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代码块捕获异常是非常重要的,因为这不可能在线程代码之外来捕获异常。原则上说,每个线程的业务异常应该在自己的内部处理完毕。

参考:

编写高质量代码改善C#程序的157个建议——建议66:正确捕获多线程中的异常

猜你喜欢

转载自www.cnblogs.com/larry-xia/p/9256840.html