C# 线程抛异常

异常抛出

  • 异常抛出要在线程代码中抛出,否则捕获不到
using System;
using System.Threading;

namespace testthread_keyword_lock
{
    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");
            }

        }
        static void badfaultyThread()
        {
            Console.WriteLine("starting a bad faulty thread ....");
            Thread.Sleep(1000);
            throw new Exception("BOOM");
        }
        static void faultyThread()
        {
            try
            {
                Console.WriteLine("starting a faulty thread.........");
                Thread.Sleep(1000);
                throw new Exception("BOOM");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception handled:{0}",ex.Message);
            }
        }
    }
}

  • 可以在app.config中使用错误策略
<configuration>
   <runtime>
       <legacyUnhandledExceptionPolicy enable="1"/>
   </runtime>
</configuration>
posted @ 2016-07-27 15:57  七夜奈何  阅读(1948)  评论(0编辑  收藏  举报