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>
上一篇:LeetCode_Next Permutation


下一篇:asp.net 树形控件 $.fn.zTree.init