gpt4 book ai didi

c# - 获取通用 Windows 应用程序错误

转载 作者:可可西里 更新时间:2023-11-01 11:14:07 25 4
gpt4 key购买 nike

如何获取 Windows 应用程序或 Windows 服务中发生的一般性错误,例如 HttpApplication 中的 Application_Error

最佳答案

您可以使用以下事件来捕获 Windows 窗体应用程序和 .Net 服务中的异常:

AppDomain.FirstChanceException

此事件每当在给定的 AppDomain 中出现异常时触发,即使事件稍后被处理也是如此。这几乎肯定不是您想要的,但我想为了完整起见我会把它包括在内。

请注意,这是一个针对每个 AppDomain 的事件 - 如果您使用多个 AppDomain,那么您需要为每个 AppDomain 处理此事件。如果您只有一个 AppDomain(更有可能),那么以下将处理此事件:

AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

static void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
throw new NotImplementedException();
}

AppDomain.UnhandledException

只要在给定的 AppDomain 中出现未处理异常,就会触发此事件。同样,这是一个每个 AppDomain 事件,并以与 FirstChanceException 事件类似的方式连接。

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new NotImplementedException();
}

您可以随时挂接这两个事件,但您可能希望尽快这样做,否则在您挂接事件处理程序之前可能会抛出异常。 Program 类中 Main 方法的开头通常是执行此操作的好地方。

请注意,在 Windows 窗体应用程序中,当您以其他方式期望它触发时,此事件可能不会被触发,因为 Windows 窗体应用程序中未处理的异常的处理方式不同(由 Windows 窗体基础结构),因此有时不会作为未处理的异常传播在 AppDomain 中。

看看Why is my Catch block only running while Debugging in Visual Studio?

Application.ThreadException

(仅适用于 Windows 窗体应用程序)

当在 Windows 窗体应用程序中抛出未处理的异常然后被 Windows 窗体基础结构捕获时,就会发生这种情况。您可能应该使用它而不是 AppDomain.UnhandledException 来捕获 Windows 窗体应用程序中未处理的异常:

Application.ThreadException += Application_ThreadException;

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
throw new NotImplementedException();
}

同样,您希望尽快将其连接起来 - Program 类中的 Main 方法的开始通常是执行此操作的好地方。

总结

请注意,它们中没有一个完全像 ASP.Net 应用程序的 Application_Error 方法,但是如果您正在创建 Windows 窗体应用程序,那么您可能 想要使用 Application.ThreadException,如果您正在创建 Windows 服务,那么您可能想要 AppDomain.UnhandledException

关于c# - 获取通用 Windows 应用程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136924/

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