In System XAML, the application is responsible for manually running a message pump and draining the DispatcherQueue during shutdown to process asynchronous tasks scheduled during the WindowsXamlManager cleanup.
System XAML Shutdown Pattern:
- Initialize
Windows::UI::Xaml::WindowsXamlManager. - Run a standard
GetMessage loop. - Call
.Close() on the WindowsXamlManager instance. - Manually drain the
DispatcherQueue using a PeekMessage loop to ensure all async work is processed. - Shut down the
DispatcherQueueController if one was created.
WinUI 3 aims to improve this by requiring the app to provide the DispatcherQueue on the thread, avoiding the issues where XAML creates a DispatcherQueueController that it cannot correctly shut down.
// System XAML Shutdown Example
auto wxm = Windows::UI::Xaml::WindowsXamlManager::InitializeForCurrentThread();
// Run the message pump
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!CallPreTranslateMessageHelper())
{
TranslateMesasge(&msg);
DispatchMessage(&msg);
}
}
// Cleanup
wxm.Close();
// Drain the DispatcherQueue to process async work
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { DispatchMessage(&msg); }
ShutdownDispatcherQueueController();