gpt4 book ai didi

c# - .NET - 实现 "catch all exceptions handler"的最佳方法是什么

转载 作者:IT王子 更新时间:2023-10-29 03:40:36 25 4
gpt4 key购买 nike

我想知道最好的方法是“如果一切都失败了”。

我的意思是,您在应用程序中处理尽可能多的异常,但仍然会有错误,所以我需要有一些东西捕获所有未处理的异常,以便我可以收集信息并存储将它们保存在数据库中或将它们提交给网络服务。

AppDomain.CurrentDomain.UnhandledException 事件是否捕获所有内容?即使应用程序是多线程的?

旁注:Windows Vista 公开了允许任何应用程序使用的 native API 函数在崩溃后自行恢复......现在想不出这个名字......但我宁愿不要使用它,因为我们的许多用户仍在使用 Windows XP。

最佳答案

我刚刚玩过 AppDomain 的 UnhandledException 行为,(这是注册未处理异常的最后阶段)

是的,在处理完事件处理程序后,您的应用程序将终止并显示令人讨厌的“...程序停止工作对话框”。

:)您仍然可以避免这种情况。

查看:

class Program
{
void Run()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Console.WriteLine("Press enter to exit.");

do
{
(new Thread(delegate()
{
throw new ArgumentException("ha-ha");
})).Start();

} while (Console.ReadLine().Trim().ToLowerInvariant() == "x");


Console.WriteLine("last good-bye");
}

int r = 0;

void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Interlocked.Increment(ref r);
Console.WriteLine("handled. {0}", r);
Console.WriteLine("Terminating " + e.IsTerminating.ToString());

Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "Dead thread";

while (true)
Thread.Sleep(TimeSpan.FromHours(1));
//Process.GetCurrentProcess().Kill();
}

static void Main(string[] args)
{
Console.WriteLine("...");
(new Program()).Run();
}
}

P.S. 请在更高级别处理未处理的 Application.ThreadException (WinForms) 或 DispatcherUnhandledException (WPF)。

关于c# - .NET - 实现 "catch all exceptions handler"的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/219594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com