Proposal: 'Yield()' APIs for 'TaskScheduler' and 'SynchronizationContext' for easy, efficient context switching in GUI apps #112257
Unanswered
Sergio0694
asked this question in
Ideas
Replies: 3 comments 3 replies
-
This should integrate seamlessly with multiple UI threads, right? In UWP each AppView has a separated UI thread. |
Beta Was this translation helpful? Give feedback.
3 replies
-
I support these changes |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Note
Opening a discussion first as suggested by @tannergooding, so we can refine the proposal (eg. the exact API name) better before moving to an issue. The idea is to avoid having a discussion that drags too much just because of secondary details in an issue.
Background and motivation
In GUI apps, it's extremely common to have to switch back and forth between different threads. The main reasons are usually that (1) most UI elements are tied to the UI thread, and will throw exceptions if accessed from anywhere else, and (2) in order to avoid stutters and dropping frames, it is very common to move work off the UI thread as much as possible, and then move back to the UI thread to signal results to the UI (eg. to update properties that are bound to the UI).
There currently is no built-in, convenient way to do these two operations. It is an extremely common pain point, and developers usually end up building the same kind of helpers for this over and over again. It also often comes up as a discussion point in C# components in Windows, where we're adopting C# in areas where before we would've used C++ (which does offer helpers for this kind of scenarios, in C++/WinRT, namely
resume_foreground
andresume_background
). Projects like Visual Studio also have equivalent helpers.Prior art
Generally speaking, there's multiple common solutions for this:
Proposal
The proposal is for two awaiters that handle switching to their associated context, something like:
Both would return an awaitable that:
Examples
The previous example would just become this:
Where
_synchronizationContext
is justSynchronizationContext.Current
, which eg. viewmodels can get in the constructor.cc. @tannergooding @stephentoub could you share your thoughts? I'd like to refine this API shape and make it into an actual proposal, which I'd hope to get into .NET 10. The topic keeps coming up, especially as we adopt C# in more places in Windows 😄
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions