任何过程中的WinForms我用:等效System.Windows.Forms.Application.ThreadException为控制台应用程序或Windows服务或一般
- System.Windows.Forms.Application.ThreadException
- 系统。 Windows.Application.UnhandledException
我应该如何使用非Winforms多线程应用程序?
考虑C#.NET 4.0以下的完整代码:
using System;
using System.Threading.Tasks;
namespace ExceptionFun
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Task.Factory.StartNew(() =>
{
throw new Exception("Oops, someone forgot to add a try/catch block");
});
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//never executed
Console.WriteLine("Logging fatal error");
}
}
}
我见过吨的计算器上类似的问题,但没有包含一个满意的答复。大多数答案都是类型:“你应该在你的代码中包含正确的exe文件处理”或者“使用AppDomain.CurrentDomain.UnhandledException”。
编辑:看来我的问题被误解了,所以我重新编写了它并提供了一个较小的代码示例。
这看起来像http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application – Jodrell 2012-07-10 11:03:24
的副本通常应该使用全局异常处理程序进行登录。如果您对异常情况有所了解,您应该在本地处理。 – Jodrell 2012-07-10 11:05:30
这应该工作得很好。当然,你不想使用try/catch,这会阻止UnhandledException事件处理程序的运行。你不必自己照顾Die(),它是自动的。 – 2012-07-10 13:14:05