如果.NET下的一個多線程程序不能正確的處理異常將很有可能會發生由於未處理異常導致進程意外終止的情況,尤其是在使用System.Threading.Timer的時候,由於TimerCallBack是在一個單獨的線程中執行的,因此在TimerCallBack方法中發生異常而沒有Catch的話將會導致未處理異常是進程意外終止。
如下的代碼所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestUnhandleException
{
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer(TimerCallback, null, 10000, 10000);
Console.ReadLine();
}
private static void TimerCallback(object obj)
{
throw new Exception("Throw a unHandledException for test");
}
}
}
上面的程序啟動后10秒鍾便會意外終止,如果查看Windows EventLog的話將會看到下面的兩條Log:
正確的做法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestUnhandleException
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Timer timer = new Timer(TimerCallback, null, 10000, 10000);
Console.ReadLine();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//Todo:Log
}
private static void TimerCallback(object obj)
{
try
{
throw new Exception("Throw a unHandledException for test");
}
catch(Exception)
{
//Todo:Log
}
}
}
}