Since Pipe_Disconnected is called by another thread, MainWindow.Close must be called by Dispatcher.
What is the difference between the codes below?
I am using .Net7.
Work
private void Pipe_Disconnected(object sender, object e)
{
Application.Current.Dispatcher.InvokeAsync(() => Application.Current.MainWindow.Close());
}
Not Work
private void Pipe_Disconnected(object sender, object e)
{
Application.Current.Dispatcher.InvokeAsync(Application.Current.MainWindow.Close);
}
Not Work
private void Pipe_Disconnected(object sender, object e)
{
var temp = new Action(Application.Current.MainWindow.Close);
Application.Current.Dispatcher.InvokeAsync(temp);
}
CodePudding user response:
The practical difference when Application.MainWindow
is being accessed.
In the first example, the property is accessed in dispatcher thread.
In the second and third it is accessed from another thread.
If you examine stacktrace of the exception, you won't see the Close method, because it is never called. The Exception is thrown when accessing MainWindows instance. The Dispatcher. InvokeAsync won't even get a chance so be called.