WindowsXamlManager.XamlShutdownCompletedOnThread 事件

定义

当 XAML 运行时在当前线程上完成其关闭过程时发生。

// Register
event_token XamlShutdownCompletedOnThread(TypedEventHandler<WindowsXamlManager, XamlShutdownCompletedOnThreadEventArgs const&> const& handler) const;

// Revoke with event_token
void XamlShutdownCompletedOnThread(event_token const* cookie) const;

// Revoke with event_revoker
WindowsXamlManager::XamlShutdownCompletedOnThread_revoker XamlShutdownCompletedOnThread(auto_revoke_t, TypedEventHandler<WindowsXamlManager, XamlShutdownCompletedOnThreadEventArgs const&> const& handler) const;
public event TypedEventHandler<WindowsXamlManager,XamlShutdownCompletedOnThreadEventArgs> XamlShutdownCompletedOnThread;
function onXamlShutdownCompletedOnThread(eventArgs) { /* Your code */ }
windowsXamlManager.addEventListener("xamlshutdowncompletedonthread", onXamlShutdownCompletedOnThread);
windowsXamlManager.removeEventListener("xamlshutdowncompletedonthread", onXamlShutdownCompletedOnThread);
- or -
windowsXamlManager.onxamlshutdowncompletedonthread = onXamlShutdownCompletedOnThread;
Public Custom Event XamlShutdownCompletedOnThread As TypedEventHandler(Of WindowsXamlManager, XamlShutdownCompletedOnThreadEventArgs) 

事件类型

示例

此示例演示当 XAML 不再在线程上运行时,如何订阅 事件以清理对象。

在此示例中,你有一些不同类型的对象,你想要在应用关闭时进行清理。 XAML 对其中一些对象有一些间接引用, (例如 Model-View-ViewModel 应用中的“模型”对象) ,因此在 XAML 完成其工作之前,你不希望销毁这些对象。 你还有一些正在另一个进程中清理的对象,并且你也希望等待这些对象。

因此,使用 XamlShutdownCompletedOnThread 事件及其延迟来组织关闭过程。 当引发此事件时,你知道 XAML 是使用此线程上的对象完成的。 还可以执行延迟,以便在远程操作完成之前不会完成关闭。

WindowsXamlManager manager = WindowsXamlManager::GetForCurrentThread();
manager.XamlShutdownCompletedOnThread([](
    const WindowsXamlManager& sender,
    const XamlShutdownCompletedOnThreadEventArgs& args) -> IAsyncAction
    {
        // Once we get this deferral, the DispatcherQueue shutdown process
        // won't continue until Complete is called.
        // Until we call deferral.Complete(), we can still use the 
        // DispatcherQueue and give it new work.
        auto deferral = args.GetDispatcherQueueDeferral();

        // Now that XAML has shutdown, we can clean up any of our objects
        // that XAML might have been using.
        CleanupUIThreadObjects();

        // Capture the UI thread context.
        winrt::apartment_context ui_thread;

        // We can also do cleanup work that might take a while. For example, 
        // we can wait for work in other processes to finish.
        co_await CleanupRemoteObjects();

        // Switch back to the UI thread, in case we have any UI-thread work left to do.
        // It will still be running because we took the deferral.
        co_await ui_thread;

        // Done! Shutdown may continue.
        deferral.Complete();
    });

注解

XAML 运行时的关闭与线程上运行的 DispatcherQueue 的关闭序列相关联。 有关详细信息,请参阅 DispatcherQueue 文档

在使用 XAML 的线程上的 DispatcherQueue 关闭时,将按顺序引发这些事件:

在引发 WindowsXamlManager.XamlShutdownCompletedOnThread 事件时:

注意

即使对 WindowsXamlManager 对象调用 Close 或释放对其的所有引用,仍会引发此事件。

适用于