c# - 发生异常且 C# 程序停止时如何调用函数?
问题描述
在 C# 程序中,当发生异常时,我想做一些动作;也就是说,当发生异常并出现异常窗口时,我想截屏并将异常的图像(以及其他信息,例如运行程序的时间和用户)保存在数据库中。请注意,在发生异常的情况下,程序会停止,直到用户单击按钮(如果用户单击退出按钮,应用程序将结束)。
解决方案
如果要捕获所有未处理的异常,则可以使用应用程序线程异常方法。
在program.cs
你需要注册线程异常,并添加一个方法来做你的处理。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//Register your thread exception method here
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
//This method will then be called and you can handle your exception anyway you wish
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
//Add your custom handling code here
}
}
推荐阅读
- reactjs - 如何使用 webpack 转换 SVG 图标?
- mongodb - Kubernetes mongodb 就绪探测失败
- c - 为什么我的#ifndef 预处理器指令在编译时不能防止包含多个标头?
- rust - 有没有办法将布尔值用作枚举的基础类型?
- html - 如何防止CSS动画在每个循环后重置
- azure - 枚举 Azure SQL Server 中的数据库列表
- android - 如何解决 Android Studio 3.2 上不存在指定的 AAPT2 可执行文件
- c++ - 通话中的参数太少
- python - 延迟文本时输出无结束
- python - 使用python将一个文件拆分为多个文件,其中包含一个关键字