2012-07-10 45 views
6

任何过程中的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”。

编辑:看来我的问题被误解了,所以我重新编写了它并提供了一个较小的代码示例。

+1

这看起来像http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application – Jodrell 2012-07-10 11:03:24

+1

的副本通常应该使用全局异常处理程序进行登录。如果您对异常情况有所了解,您应该在本地处理。 – Jodrell 2012-07-10 11:05:30

+0

这应该工作得很好。当然,你不想使用try/catch,这会阻止UnhandledException事件处理程序的运行。你不必自己照顾Die(),它是自动的。 – 2012-07-10 13:14:05

回答

0

您不需要任何等价物,CurrentDomain.UnhandledException事件在多线程控制台应用程序中工作得很好。但由于你开始线程的方式,它并没有解决你的问题。您的问题中的处理程序不会在Windows和控制台应用程序中执行。但是,如果你像这样开始你的线程(例如):

new Thread(() => { 
    throw new Exception("Oops, someone forgot to add a try/catch block"); 
}).Start(); 

它会着火。

Task.Factory.StartNew(...)CurrentDomain.UnhandledException问题在SO上的很多帖子中被讨论过。查了一些建议,在这里:

How to handle all unhandled exceptions when using Task Parallel Library?

What is the best way to catch exception in Task?

相关问题