6

在 WinForms 我使用:

  • System.Windows.Forms.Application.ThreadException
  • System.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");
        }
    }
}

我在 stackoverflow 上看到了大量类似的问题,但没有一个包含令人满意的答案。大多数答案都是类型:“您应该在代码中包含正确的异常处理”或“使用 AppDomain.CurrentDomain.UnhandledException”。

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

4

1 回答 1

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 上的许多帖子中都有讨论。在这里查看一些建议:

使用任务并行库时如何处理所有未处理的异常?

在任务中捕获异常的最佳方法是什么?

于 2015-01-18T14:25:28.443 回答