本文主要说明:在线程函数中使用Try Catch能够正确捕获异常,而如果使用形如 try { var t = New Thread(XX); t.start(); } Catch{} 这种代码是无法正确处理异常的。
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("无法在此处捕获错误!");
}
Console.Read();
}
static void BadFaultyThread()
{
Console.WriteLine("Starting a faulty thread...");
Thread.Sleep(2000);
throw new Exception("Boom!");
}
static void FaultyThread()
{
try
{
Console.WriteLine("St