在WinForms中我使用:
我应该将什么用于非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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在stackoverflow上看到了大量类似的问题,但没有一个包含令人满意的答案.大多数答案都是类型:"您应该在代码中包含正确的exeption处理"或"使用AppDomain.CurrentDomain.UnhandledException".
编辑:似乎我的问题被误解了,所以我重新制定了它并提供了一个较小的代码示例.
您不需要任何等效项,该CurrentDomain.UnhandledException事件在多线程控制台应用程序中运行良好。但由于您启动线程的方式,它不会在您的情况下触发。您问题中的处理程序不会在 Windows 和控制台应用程序中执行。但是如果你像这样开始你的线程(例如):
new Thread(() => {
throw new Exception("Oops, someone forgot to add a try/catch block");
}).Start();
Run Code Online (Sandbox Code Playgroud)
它会着火。
SO 上的许多帖子都讨论了这个Task.Factory.StartNew(...)问题。CurrentDomain.UnhandledException在这里检查一些建议:
| 归档时间: |
|
| 查看次数: |
1733 次 |
| 最近记录: |