Search code examples
wpfmultithreadingapplication-shutdown

How to synchronously shutdown WPF application?


App.Current.Shutdown() works asynchronously. It means that when you invoke this method you are not protected from execution of lines of code which follow the invokation of Shutdown().

So the question is how to block a thread from which App.Current.Shutdown() is invoked?

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

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        App.Current.Shutdown();

        File.WriteAllText(@"..\log.txt", "Info");    
    }
}

 private void App_OnExit(object sender, ExitEventArgs e) {
        Thread.Sleep(3500);
    }

File.WriteAll will create a new file and write into it "Info" string.


Solution

  • App.Current.Shutdown() is not working asynchronously according to documentation: http://msdn.microsoft.com/en-us/library/ms597013.aspx

    Application.Current.Dispatcher.BeginInvokeShutdown() is working async.

    UPD

    I've tested your code. You are right. And documentation about App.Current.Shutdown() is misleading. Code after App.Current.Shutdown() in current method will be executed. Therefore App.Current.Shutdown should be the last statement before return (and also respecting method call tree).

    As alternative to call Environment.Exit(0) but it could be considered as trick and hack, because in the fact it terminates process either gracefully or not, when gracefully isn't possible.