不调用Application.ThreadException

时间:2013-06-04 07:59:25

标签: c# .net winforms exception exception-handling

我的WinForms应用程序安装Application.ThreadException事件处理程序来处理所有未处理的异常(处理程序显示一个对话框:出现错误,单击此处发送错误报告等)。

问题是当应用程序显示模式对话框时,不会调用我的事件处理程序。当我显示MessageBox或我的异常对话框时,将以静默方式吞下所有异常。有没有办法抓住他们?

下面是一个模拟此行为的WinForms应用程序示例。当此应用程序显示MessageBox时,后台抛出的所有异常都将丢失(不会调用ThreadException处理程序):

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

class Program
{
  static void Main()
  {
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    var form = new MyForm();
    Application.ThreadException += (s, e) =>
    {
        form.AppendText("ThreadException event handler is called.");
        MessageBox.Show("Error: " + e.Exception);
    };

    Application.EnableVisualStyles();
    Application.Run(form);
  }
}

class MyForm : Form
{
  public MyForm()
  {
    Controls.Add(TextBox = new TextBox
    {
      Multiline = true,
      Dock = DockStyle.Fill
    });

    ThrowUnhandledException(1);
    ThrowUnhandledException(2);
    ThrowUnhandledException(3);
  }

  private async void ThrowUnhandledException(int delaySeconds)
  {
    await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
    AppendText("Throwing a NotImplementedException!");
    throw new NotImplementedException();
  }

  private TextBox TextBox { get; set; }

  public void AppendText(string message)
  {
    TextBox.AppendText(message + Environment.NewLine);
  }
}

修改。我已经更新了代码以使事情更加清晰。

当抛出异常时,MyForm会写入TextBox:抛出NotImplementedException!

当调用ThreadException处理程序时,它会写:调用ThreadException事件处理程序。然后它会显示一个消息框。

如果捕获了所有异常,我的TextBox将显示以下内容:

Throwing a NotImplementedException!
ThreadException event handler is called.
Throwing a NotImplementedException!
ThreadException event handler is called.
Throwing a NotImplementedException!
ThreadException event handler is called.

但它显示:

Throwing a NotImplementedException!
ThreadException event handler is called.
Throwing a NotImplementedException!
Throwing a NotImplementedException!

2 个答案:

答案 0 :(得分:2)

您可以尝试替换

Application.ThreadException += (s, e) => MessageBox.Show("Error: " + e.Exception);

Application.ThreadException += (s, e) => Console.WriteLine(e.Exception); 

您将看到每次都会调用事件处理程序。

答案 1 :(得分:0)

我试过你的程序,但似乎对我来说很好。 ThrowUnhandledException被调用3次。所有三条消息都附加到TextBox。

我尝试添加MessageBox:

ThrowUnhandledException(1);
ThrowUnhandledException(2);
ThrowUnhandledException(3);

MessageBox.Show("Hello");

但是也可以按预期工作。我得到了消息框但是如果我在异常处理程序上放置一个断点,它会被调用三次。当我关闭消息框时,我可以在MyForm窗口中看到所有三条消息。