Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

I created a simple WPF application and replicated your code. The shutdown is not working asynchronously in it. The application was closed immediately when i click the close button.

 <Grid>
    <Button x:Name="btnClose" Height="50" Width="100"  Click="btnClose_Click_1"  Margin="265,135,152,135">Close</Button>
</Grid>**strong text**

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnClose_Click_1(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

            MessageBox.Show("test");
        }

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

else

You can then kill the process by using Process.GetCurrentProcess().Kill();

use System.Diagnostics namespace for it. This will work fine for you

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top