diff --git a/src/cascadia/WindowsTerminal/WindowEmperor.cpp b/src/cascadia/WindowsTerminal/WindowEmperor.cpp index 9e851dcf8fe..dcccce3a316 100644 --- a/src/cascadia/WindowsTerminal/WindowEmperor.cpp +++ b/src/cascadia/WindowsTerminal/WindowEmperor.cpp @@ -140,7 +140,7 @@ void WindowEmperor::_createNewWindowThread(const Remoting::WindowRequestedArgs& std::thread t([weakThis, window]() { try { - const auto cleanup = wil::scope_exit([&]() { + auto cleanup = wil::scope_exit([&]() { if (auto self{ weakThis.lock() }) { self->_windowExitedHandler(window->Peasant().GetID()); @@ -155,6 +155,16 @@ void WindowEmperor::_createNewWindowThread(const Remoting::WindowRequestedArgs& } window->RunMessagePump(); + + // Manually trigger the cleanup callback. This will ensure that we + // remove the window from our list of windows, before we release the + // AppHost (and subsequently, the host's Logic() member that we use + // elsewhere). + cleanup.reset(); + + // Now that we no longer care about this thread's window, let it + // release it's app host and flush the rest of the XAML queue. + window->RundownForExit(); } CATCH_LOG() }); diff --git a/src/cascadia/WindowsTerminal/WindowThread.cpp b/src/cascadia/WindowsTerminal/WindowThread.cpp index 398a36e16dd..14cafb7b79b 100644 --- a/src/cascadia/WindowsTerminal/WindowThread.cpp +++ b/src/cascadia/WindowsTerminal/WindowThread.cpp @@ -37,7 +37,11 @@ int WindowThread::RunMessagePump() // Enter the main window loop. const auto exitCode = _messagePump(); // Here, the main window loop has exited. + return exitCode; +} +void WindowThread::RundownForExit() +{ _host = nullptr; // !! LOAD BEARING !! // @@ -54,8 +58,6 @@ int WindowThread::RunMessagePump() ::DispatchMessageW(&msg); } } - - return exitCode; } winrt::TerminalApp::TerminalWindow WindowThread::Logic() diff --git a/src/cascadia/WindowsTerminal/WindowThread.h b/src/cascadia/WindowsTerminal/WindowThread.h index fecee558876..86b0854639e 100644 --- a/src/cascadia/WindowsTerminal/WindowThread.h +++ b/src/cascadia/WindowsTerminal/WindowThread.h @@ -15,6 +15,7 @@ class WindowThread : public std::enable_shared_from_this winrt::TerminalApp::TerminalWindow Logic(); void CreateHost(); int RunMessagePump(); + void RundownForExit(); winrt::Microsoft::Terminal::Remoting::Peasant Peasant();