假设我有以下的控制台程序,是否可以让整个程序不因为后台的异常而崩溃?
Thread thread = new Thread(new ThreadStart(() => { throw new Exception(); }));
thread.IsBackground = true;
thread.Start();
while (true)
Console.WriteLine("Hello from main thread");
能否让整个程序不会因为后台异常而崩溃(当然不用try…catch)?
解决方案:
附加你的未处理异常处理程序。http:/msdn.microsoft.comen-uslibrarysystem.appdomain.unhandledexception.aspx。
更好的方法是用全局处理程序来达到预期的结果(好吧,用trycatch,但只有一次)。
public static void GlobalHandler(ThreadStart threadStartTarget)
{
try
{
threadStartTarget.Invoke();
}
catch (Exception ex)
{
//handle exception here
}
}
然后启动你的线程:
Thread thread = new Thread(o => GlobalHandler(ThreadMethod));
thread.Start();
P.S. 然而,我真的不喜欢捕捉所有异常的想法。它是 几乎 从来都不是好主意。