4

App.Current.Shutdown()异步工作。这意味着当您调用此方法时,您不受保护,不会执行调用 Shutdown() 之后的代码行。

所以问题是如何阻止调用 App.Current.Shutdown() 的线程?

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 将创建一个新文件并将“Info”字符串写入其中。

4

2 回答 2

4

App.Current.Shutdown()根据文档不能异步工作:http: //msdn.microsoft.com/en-us/library/ms597013.aspx

Application.Current.Dispatcher.BeginInvokeShutdown()正在异步工作。

UPD

我已经测试了你的代码。你说的对。关于的文档App.Current.Shutdown()具有误导性。当前方法中的代码App.Current.Shutdown()将被执行。因此App.Current.Shutdown应该是 return 之前的最后一条语句(并且也尊重方法调用树)。

作为 call 的替代方法,Environment.Exit(0)但它可以被视为技巧和黑客攻击,因为事实上,当优雅地不可能时,它会优雅地或不优雅地终止进程。

于 2013-04-29T09:20:04.293 回答
0

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

于 2013-04-29T09:06:57.303 回答