为什么WPF吞下抛出的事件处理程序Window.Activated一个例外?抛出、吞下、事件、程序

2023-09-04 13:42:38 作者:酒醉夜未阑

简单的WPF应用程序有一个简单的,空的窗口中,我将计算机与事件处理程序窗口的激活事件:

Simple WPF app with a plain, empty Window in which I hook up an event handler to the Window's Activated event:

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        Activated += OnWindowActivated;
    }

    private void OnWindowActivated(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

当一个异常被抛出的处理程序和未处理的其他地方,我希望应用程序死,但事实并非如此。 WPF似乎某处吞咽异常,窗口弹出,并继续运行就好了。

When an exception is thrown in the handler and unhandled anywhere else, I expected the app to die, but it doesn't. WPF seems to be swallowing the exception somewhere and the Window pops up and keeps on running just fine.

为什么?

推荐答案

这可能与在64位操作系统上运行32位应用程序的问题。如果是这样的话,那么通过保罗·贝茨应该给你一个好主意,发生了什么事。

This could be an issue related to running 32-bit applications on a 64-bit operating system. If that is the case then the blog post by Paul Betts should give you a good idea what is happening.

在总之,它看起来像32位处理.NET框架吃你的例外,由于与整个用户模式/内核模式的界限异常的传播问题。对于64位进程这不会发生,所以测试的最简单的方式,如果这确实是你的问题是重建你的测试应用程序使用的'任何CPU'的平台,然后再次运行它。当我这样做,坠毁正如人们所期望的那样。

In short it looks like for 32-bit processes the .NET framework eats your exceptions due to issues with the propagation of the exception across user-mode / kernel mode boundaries. For 64-bit processes this doesn't happen, so the simplest way to test if this is indeed your problem is to rebuild your test app with for the 'Any CPU' platform and run it again. When I did that it crashed as one would expect.