私はさらにいくつかのテストを行いました、そして今私は違いを知っていると思います:
1)MSDNページに記載されているようにBeginInvokeShutdown
、ディスパッチャをシャットダウンするだけでなく、キューをクリア/中止します。Shutdown
最初に、ディスパッチャキュー内のすべてのアイテムを処理します。
シャットダウンプロセスが開始されると、キュー内の保留中のすべての作業項目が中止されます。
2)アプリケーションでは、Application.Exitイベントを処理できます。このイベントは、Shutdownを呼び出すと発生しますが、BeginInvokeShutdownを呼び出すと発生しません。同じことがWindow.ClosingとWindow.Closedにも当てはまります。
類似点については、どちらの場合もメインスレッドが終了します。実行中の他のスレッドによっては、これによってプロセスもシャットダウンされます。バックグラウンド以外のスレッドは、プロセスが終了する前に最後まで実行されます。
以下は私のテストコードです。Application_Startupのいずれかのメソッド呼び出しにコメントを付けます。
public partial class App
{
private void Application_Exit(object sender, ExitEventArgs e)
{
MessageBox.Show("Exiting");
}
private void Application_Startup(object sender, StartupEventArgs e)
{
var testThread = new Thread(
() =>
{
Thread.Sleep(2000);
Application.Current.Dispatcher.BeginInvokeShutdown(System.Windows.Threading.DispatcherPriority.Send);
//Application.Current.Dispatcher.BeginInvoke(new Action(() => Application.Current.Shutdown()));
});
testThread.Start();
}
}
public partial class Window1
{
public Window1()
{
this.InitializeComponent();
Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(1000);
Console.WriteLine("One");
}));
Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Two");
}));
Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Three");
}));
Dispatcher.BeginInvoke(new Action(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Four");
}));
}
private void Window_Closed(object sender, EventArgs e)
{
Console.WriteLine("Closed");
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Console.WriteLine("Closing");
}
}