UWP C++/WinRT: Asynchronous Sleep

1.2k Views Asked by At

How can I wait a specific amount of time without blocking the UI thread? I'm looking for await Task.Delay() equivalent in C++/WinRT.

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));
}

Edit:

A possible solution is to call Sleep(ms) on a background thread.

winrt::apartment_context ui_thread; // Capture calling context.
co_await winrt::resume_background();
Sleep(1000);
co_await ui_thread; // Switch back to calling context.

This works, but I still believe there is a better way of doing so.

1

There are 1 best solutions below

0
YanGu On

You could try to work in a separate thread by submitting a work item to the thread pool, which can maintain a responsive UI while still completing work that takes a noticeable amount of time. Refer to the document for more information about how to submit a work item to the thread pool.

You could check the following as a sample:

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"));
}