如何在 C++/winrt 中调用 GUI 线程上的方法

How to call a method on the GUI thread in C++/winrt

在使用 C++/winrt 响应文本框中的事件时,我需要使用 ScrollViewer.ChangeView()。问题是,调用执行时什么也没有发生,我想那是因为那一刻代码在错误的线程中;我读到这是 ChangeView() 缺少可见结果的原因。看来正确的做法是使用 CoreDispatcher.RunAsync 更新 UI 线程上的滚动条。然而,仅在 C# 和托管 C++ 中提供了此示例代码,要弄清楚它在普通 C++ 中的外观是一件棘手的事情。无论如何,我不明白。有没有人有在 C++/winrt 中的 UI 线程上调用方法的正确方法的示例?谢谢

[更新:]我发现了另一种似乎有效的方法,我将在此处展示,但我仍然对上述问题的答案感兴趣。另一种方法是创建一个 IAsyncOperation,归结为:

IAsyncOperation<bool> ScrollIt(h,v, zoom){
   co_await m_scroll_viewer.ChangeView(h,v,zoom);
}

文档条目 Concurrency and asynchronous operations with C++/WinRT: Programming with thread affinity in mind 解释了如何控制哪个线程运行特定代码。这在异步函数的上下文中特别有用。

C++/WinRT 提供助手 winrt::resume_background()winrt::resume_foreground()co_await-ing 任一切换到相应的线程(后台线程,或与控件的调度程序关联的线程)。

下面的代码说明了用法:

IAsyncOperation<bool> ScrollIt(h, v, zoom){
    co_await winrt::resume_background();
    // Do compute-bound work here.

    // Switch to the foreground thread associated with m_scroll_viewer.
    co_await winrt::resume_foreground(m_scroll_viewer.Dispatcher());
    // Execute GUI-related code
    m_scroll_viewer.ChangeView(h, v, zoom);

    // Optionally switch back to a background thread.        

    // Return an appropriate value.
    co_return {};
}