当我的应用程序崩溃时,我尝试记录异常。尽管偶尔会捕获大多数异常,但我的应用程序崩溃了。我真的不知道如何将异常记录到文本文件中。无论我尝试什么似乎都不起作用。我不确定自己做错了什么,如果有人能指出我正确的方向,我将不胜感激。
这就是我的代码当前的样子。我使用的是多线程环境。
public MainWindow()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
InitializeComponent();
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
using (StreamWriter writer = File.AppendText("ExceptionsLog.txt"))
{
DateTime time = DateTime.Now;
writer.WriteLine("Time {0} Exception: {1} Runtime termination: {2}", time, e.Message, args.IsTerminating);
}
}
最佳答案
首先,请确保刷新您的 StreamWriter
。
其次,可能还有 AppDomain.CurrentDomain.UnhandledException
未报告的其他异常。
如果您正在使用任务,它们可能会导致触发
TaskScheduler.UnobservedTaskException
事件。如果您使用的是 WPF,您可能还需要处理
Application.Current.DispatcherUnhandledException
事件,以防止进程崩溃。如果您使用多个应用域,则当前域不会处理其中的异常。
关于c# - 记录致命异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21411222/