July 21st, 2025
0 reactions

What happens if C++/WinRT is unable to resume execution on a dispatcher thread?

The C++/WinRT library provides the winrt::resume_foreground() function for resuming a coroutine on the foreground thread of a dispatcher. It supports three types of dispatchers: Windows.UI.Core.CoreDispatcher, Windows.System.DispatcherQueue, Microsoft.UI.Dispatching.DispatcherQueue.

But what happens if the thread switch fails? This happens if the dispatcher thread is no longer accepting new work, either because it is shutting down, or because it no longer exists at all.

If a Core­Dispatcher is unable to dispatch a work item, it silently releases the work item without executing it. For winrt::resume_foreground(), that means that your coroutine appears to hang. The resumption never happens, nothing in the coroutine executes beyond the co_await winrt::resume_foreground(core­Dispatcher), and your coroutine is leaked.

If either of the Dispatcher­Queue objects is unable to dispatch a work item, then the Try­Enqueue() method returns false. The winrt::resume_foreground() function propagates this return value as the return value of co_await. This means that you are expected to check the return value to find out whether the thread switch is successful.

if (co_await winrt::resume_foreground(dispatcherQueue))
{
    // Yay, executing on the dispatcher thread
} else
{
    // Rats, was not able to switch threads
}

In practice, nobody¹ checks the return value of co_await winrt::resume_foreground(dispatcher­Queue), so the result is that the code continues running on the wrong thread. It thinks that it’s on the dispatcher thread, but it’s not.

This sure looks like a disaster. We’ll find an escape route next time.

¹ I have yet to find any code in any code base that checks the return value. Not even the C++/WinRT unit tests check the return value!

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