如何从WPF中的线程冒出错误并防止应用程序崩溃

时间:2013-11-24 16:47:49

标签: c# wpf

我正在尝试学习如何在WPF中记录错误并保持应用程序运行。我发现DispatcherUnhandledException不会捕获线程内的错误,所以我也使用currentDomain.UnhandledException

在下面的示例中,我的错误被捕获并记录,但应用程序仍然崩溃。如何记录错误但阻止应用程序崩溃?

Problem signature:
  Problem Event Name:   CLR20r3
  Problem Signature 01: test.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 5292262f
  Problem Signature 04: test
  Problem Signature 05: 1.0.0.0
  Problem Signature 06: 5292262f
  Problem Signature 07: 24b
  Problem Signature 08: 6
  Problem Signature 09: System.DivideByZeroException 

App.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

}

static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
    Exception theException = (Exception)args.ExceptionObject;
    string theErrorPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\GeneratorTestbedError23.txt";
    using (System.IO.TextWriter theTextWriter = new System.IO.StreamWriter(theErrorPath, true))
    {
        DateTime theNow = DateTime.Now;
        theTextWriter.WriteLine("The error time: " + theNow.ToShortDateString() + " " +
                                theNow.ToShortTimeString());
        while (theException != null)
        {
            theTextWriter.WriteLine("Exception: " + theException.ToString());
            theException = theException.InnerException;
        }
    }

}

private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    Exception theException = e.Exception;
    string theErrorPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) +
                          "\\GeneratorTestbedError.txt";
    using (System.IO.TextWriter theTextWriter = new System.IO.StreamWriter(theErrorPath, true))
    {
        DateTime theNow = DateTime.Now;
        theTextWriter.WriteLine("The error time: " + theNow.ToShortDateString() + " " +
                                theNow.ToShortTimeString());
        while (theException != null)
        {
            theTextWriter.WriteLine("Exception: " + theException.ToString());
            theException = theException.InnerException;
        }
    }

    MessageBox.Show("The program crashed.  A stack trace can be found at:\n" + theErrorPath);
    e.Handled = true;
    //Application.Current.Shutdown();
}

MainWindow.xaml.cs:

Public MainWindow()
{
    try
    {
        testForErrors();
    }
    catch (Exception ex)
    {
        throw;
    }
}

private void testForErrors()
{
        var th = new Thread(() =>
        {
            throw new System.DivideByZeroException();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.IsBackground = true;
        th.Start();
}

0 个答案:

没有答案