首页 > 解决方案 > 如何链接对 Application.ThreadException 的调用?

问题描述

在 WinForms 应用程序 (.NET 4.5.1) 中,如果我将多个处理程序添加到Application.ThreadException仅调用最近添加的处理程序。我在文档中的任何地方都没有看到这一点。事实上它声明,“附加你的事件处理程序......”注意“处理程序”的复数形式。

这是一个说明该行为的示例:

internal class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.ThreadException +=
            (sender, args) => Console.WriteLine(@"This is never printed");
        Application.ThreadException +=
            (sender, args) => Console.WriteLine(@"Only this is printed");

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public Form1()
    {
        var button = new Button {Text = @"CRASH!"};
        button.Click += (sender, args) => throw new NotImplementedException();
        Controls.Add(button);
    }
}

有没有办法检索现有的处理程序并从我自己的处理程序中调用它?我问的原因是我正在尝试将新的 MS AppCenter SDK 集成到我的应用程序中,并将处理程序添加到Application.ThreadException. 我想添加自己的处理程序,但在发生异常时仍调用 AppCenter 处理程序。

这是一个伪代码,说明了我想要做什么:

static void Main()
{
    AppCenter.Start("id", typeof(Crashes));
    var handler = GetCurrentThreadExceptionHandler();
    Application.ThreadException += (sender, args) => {
        handler?.Invoke(sender, args);
        Log("Something happened");
        new UnhandledErrorDialog().Show();
    };
}

标签: c#.netwinforms.net-4.5

解决方案


推荐阅读