Lets take a simple WPF application with two Window classes. The MainWindow has a single control - button - which creates AnotherWindow instance. 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.
A workaround for that is to set a new window's Owner
property to the MainWindow object instance.
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.
Questions:
Where is such behaviour of WPF window threads is described?
What is the best practice for creating other windows with an exception possibility keeping in mind: set window's
Owner
, callwindow.Close()
in somefinally
scope or something else?
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();
}
}