如何在不阻塞UI线程的情况下等待特定的时间量?我正在寻找C++/WinRT中的await Task.Delay()等价物。
IAsyncAction MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
const auto& requestResponse{ co_await HttpClient{}.GetStringAsync(Uri{ L"https://pastebin.com/raw/1j9EAVUW" }) };
Sleep(1000); // This does block UI and makes UI not responsive.
await Task.Delay(1000); // This would work in C#, but is not a thing in C++.
myButton().Content(box_value(requestResponse));
}编辑:
一种可能的解决方案是在后台线程上调用Sleep(ms)。
winrt::apartment_context ui_thread; // Capture calling context.
co_await winrt::resume_background();
Sleep(1000);
co_await ui_thread; // Switch back to calling context.这是可行的,但我仍然相信有一种更好的方法。
发布于 2021-01-08 15:18:10
您可以尝试通过将工作项提交到线程池来在单独的线程中工作,线程池可以维护响应式UI,同时仍然可以完成需要大量时间的工作。有关如何submit a work item to the thread pool的详细信息,请参阅文档。
您可以将以下内容作为示例进行检查:
IAsyncAction MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
co_await Windows::System::Threading::ThreadPool::RunAsync([&](Windows::Foundation::IAsyncAction const& workItem)
{
Sleep(1000);
});
myButton().Content(box_value(L"Clicked"));
}https://stackoverflow.com/questions/65551060
复制相似问题