April 29th, 2024

Awaiting a set of handles in C++/WinRT

C++/WinRT provides the resume_on_signal awaiter that allows you to await until a kernel handle is signaled. What if you have a bunch of these handles, and you want to await until all of them are signaled?

It turns out that this is easier than it sounds. We can use the same trick as we used in our basic when_all function: Just await each handle in sequence.

winrt::Windows::Foundation::IAsyncAction
    when_all_signaled(std::vector<HANDLE> handles)
{
    for (auto handle : handles) {
        co_await winrt::resume_on_signal(handle);
    }
}

If you want to accept the handles varadically, then it’s the one-liner we saw before:

template<typename... Handles>
winrt::Windows::Foundation::IAsyncAction
    when_all_signaled(Handles... handles)
{
    (co_await winrt::resume_on_signal(handles), ...);
}

Things get more complicated if we want to await a set of handles with a timeout. That’s what we’ll be looking at for the next few days.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.