winrt::apartment_context considered harmful #17340

Closed
opened 2026-01-31 05:39:42 +00:00 by claunia · 1 comment
Owner

Originally created by @zadjii-msft on GitHub (Apr 26, 2022).

We should try to avoid using winrt::apartment_context as it's inherently flawed unfortunately. 😥
As Raymond Chen wrote:

Unfortunately, it's true. co_await'ing an apartment_context is blocking [the background thread]. That's because it's built out of COM's IContextCallback, which supports only synchronous transfer.
[...]
Note that it's even worse: Even after you get to the other side, the side you came *from* is still blocked until you finish doing your other-side work (which could take the form of another co_await).
[...]
If the UI thread is hung, this will lead to threadpool starvation and eventually a deadlock.

_GetWindowLayoutAsync() in particular is quite dangerous because it uses an apartment_context to switch back to a background thread and blocks the UI thread for that duration...

Originally posted by @lhecker in https://github.com/microsoft/terminal/pull/12979#discussion_r858680237

Originally created by @zadjii-msft on GitHub (Apr 26, 2022). We should try to avoid using `winrt::apartment_context` as it's inherently flawed unfortunately. 😥 As Raymond Chen wrote: > Unfortunately, it's true. co_await'ing an `apartment_context` is blocking [the background thread]. That's because it's built out of COM's `IContextCallback`, [which supports only synchronous transfer](https://devblogs.microsoft.com/oldnewthing/20191128-00/?p=103157). > [...] > Note that it's even worse: Even after you get to the other side, the side you came **\*from\*** is still blocked until you finish doing your other-side work (which could take the form of another co_await). > [...] > If the UI thread is hung, this will lead to threadpool starvation and eventually a deadlock. `_GetWindowLayoutAsync()` in particular is quite dangerous because it uses an `apartment_context` to switch back to a background thread and blocks the UI thread for that duration... _Originally posted by @lhecker in https://github.com/microsoft/terminal/pull/12979#discussion_r858680237_
Author
Owner

@zadjii-msft commented on GitHub (Apr 26, 2022):

We should fix any uses of that.

@zadjii-msft commented on GitHub (Apr 26, 2022): We should fix any uses of that.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/terminal#17340