简体   繁体   English

C# WPF 当新创建的 Window 出现异常时,应用程序在退出后继续运行

[英]C# WPF Application keeps running after the exit when a new created Window is followed with an Exception

Lets take a simple WPF application with two Window classes.让我们看一个简单的 WPF 应用程序,它有两个 Window 类。 The MainWindow has a single control - button - which creates AnotherWindow instance. MainWindow 有一个控件 - 按钮 - 它创建了 AnotherWindow 实例。 If an Exception happens after the creation before the main thread exits ButtonMethod scope, then the application remains running after the MainWindow is closed and disappeared.如果在创建之后在主线程退出ButtonMethod scope之前发生异常,那么在主窗口关闭并消失后应用程序仍然运行。

A workaround for that is to set a new window's Owner property to the MainWindow object instance.一种解决方法是将新窗口的Owner属性设置为 MainWindow object 实例。

The app will also keeps running even without any exception throwing if there would be no w.Show() or w.Close() call after an instance of AnotherWindow is created.如果在创建另一个窗口的实例后没有w.Show()w.Close()调用,即使没有任何异常抛出,该应用程序也将继续运行。

Questions:问题:

  • Where is such behaviour of WPF window threads is described? WPF window 线程的这种行为在哪里描述?

  • What is the best practice for creating other windows with an exception possibility keeping in mind: set window's Owner , call window.Close() in some finally scope or something else?创建其他 windows 的最佳实践是记住异常可能性:设置窗口的Ownerfinally在 scope 中调用window.Close()或其他什么?

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ButtonMethod();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void ButtonMethod()
        {
            Window w = new AnotherWindow();
            // Uncomment the line below to fix freezing at the exit.
            // w.Owner = this;
            throw new Exception("Custom user exception!");
            w.Show();
        }
    }

To open a new window on wpf you use this code:要在 wpf 上打开新的 window,请使用以下代码:

private void Button_Click(object sender, RoutedEventArgs e)
{
    SecondWindow w = new SecondWindow();
    w.Show();
}

And if you wish to close the one you're on is:如果你想关闭你正在使用的那个是:

This.close();

You don't need the code你不需要代码

throw new Exception("Custom user exception;");

Because you're just making an exception which you are catching anyways, you throw an exception (typically) when you want to debug your code or to see if it's catching the right type of exceptions.因为您只是在制造一个无论如何都要捕获的异常,所以当您想要调试代码或查看它是否捕获正确类型的异常时(通常)会抛出异常。 I hope I helped.我希望我有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM