Open Sergio0694 opened 4 years ago
@marb2000 FYI
In my scenario, I have a web socket client that is shared across multiple windows. I see two options for displaying content I get from that connection: I could keep redundant instances of my models in the page associated with the window and update them on the page’s dispatcher through events fired by web socket messages, or I could share all the models throughout the windows. I would rather do the second, as it would be much simpler and keep everything consolidated. But here lies the problem—I want to bind my UI to those models.
Here’s what happens:
That was expected (but unwelcome). I don’t want my web socket class to have a concept of a UI thread, though. But what if I run the change on the Dispatcher of the page, anyway?
Dispatcher.RunAsync
Great. The UI has been updated. But now I open another window, and as soon as the web socket receives a new message, my app will crash. What happened?
Dispatcher.RunAsync
None of this is ideal (and I have no solution at all for binding to the same object from different windows), and I very much support changing the generated code to run property changes on the correct thread without having to manually call anything. That would solve my two problems: the improper separation of concerns (my web socket class should not care whether there is a UI thread or not) and the inability to update a property bound to UI on different threads.
For consistency I would expect same behaviour with old-style Binding as well.
Thank you for chiming in @BreeceW! Yes that's exactly one of the reasons why having this functionality be built-in would be great, and why handling the "UI thread" on the backend side (like some MVVM libraries do) is not only impractical and breaking the framework-agnostic architecture, but also still not a proper solutions if you have in fact more than one UI thread 👍
Just spotted a minor codegen issue in my original proposal, updating it now 😄
This part:
if (dispatcherQueue.HasThreadAccess)
{
PropertyChanged_ViewModel_OnDispatcherQueue(sender, e);
}
else
{
_ = dispatcherQueue.TryEnqueue(() => PropertyChanged_ViewModel_OnDispatcherQueue(sender, e));
}
Actually causes the C# compiler to always allocate the closure class used in the second branch, even when we don't actually need it at all. This would introduce unnecessary allocations even when the dispatch is not actually done, see:
<>c__DisplayClass1_0 <>c__DisplayClass1_ = new <>c__DisplayClass1_0();
<>c__DisplayClass1_.<>4__this = this;
<>c__DisplayClass1_.obj = obj;
<>c__DisplayClass1_.e = e;
if (dispatcherQueue.HasThreadAccess)
{
PropertyChanged_ViewModel_OnDispatcherQueue(<>c__DisplayClass1_.obj, <>c__DisplayClass1_.e);
}
else
{
dispatcherQueue.TryEnqueue(new Action(<>c__DisplayClass1_.<PropertyChanged_ViewModel>b__0));
}
The simple solution is just to move the dispatch in a separate, non-inlined method, like so:
public void PropertyChanged_ViewModel(object obj, global::System.ComponentModel.PropertyChangedEventArgs e)
{
if (dispatcherQueue.HasThreadAccess) PropertyChanged_ViewModel_OnDispatcherQueue(obj, e);
else PropertyChanged_ViewModel_Dispatch(obj, e);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void PropertyChanged_ViewModel_Dispatch(Object obj, global::System.ComponentModel.PropertyChangedEventArgs e)
{
_ = dispatcherQueue.TryEnqueue(() => PropertyChanged_ViewModel_OnDispatcherQueue(obj, e));
}
Which results in the correct codegen here:
public void PropertyChanged_ViewModel(object obj, PropertyChangedEventArgs e)
{
if (dispatcherQueue.HasThreadAccess)
{
PropertyChanged_ViewModel_OnDispatcherQueue(obj, e);
}
else
{
PropertyChanged_ViewModel_Dispatch(obj, e);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void PropertyChanged_ViewModel_Dispatch(object obj, PropertyChangedEventArgs e)
{
<>c__DisplayClass2_0 <>c__DisplayClass2_ = new <>c__DisplayClass2_0();
<>c__DisplayClass2_.<>4__this = this;
<>c__DisplayClass2_.obj = obj;
<>c__DisplayClass2_.e = e;
dispatcherQueue.TryEnqueue(new Action(<>c__DisplayClass2_.<PropertyChanged_ViewModel_Dispatch>b__0));
}
Where the overhead/allocation is only paid if we do need to dispatch (which is expected anyway). In all cases where we're already on the right thread, the performance would be just like before 🚀
Thank you for this @Sergio0694. We would be able to look into this more post WinUI 3.0. I will leave this open for now.
As this would make every developer's life easier and it seems straightforward to implement, can we create a list a list of reasons why it can't or shouldn't be done ASAP?
We have entered that "post WinUI 3.0" phase after all...
@Sergio0694 @andrewleader @ryandemopoulos
"can we create a list a list of reasons why it can't or shouldn't be done ASAP?"
I can list a few off the top of my head:
INotifyPropertyChanged
. You'd need to also adapt it to support INotifyCollectionChanged
for it to be consistent. Still doable, but it's a bit more work.INotifyDataErrorInfo
.Not saying this means it shouldn't be done - I do think this has been a major issue with the platform since WPF first came out, and I do think it'd be worth it to make this change. Just saying it's still a fair amount of work and not just a 5 minutes commit 😄
🦙 Link back to similar issue https://github.com/microsoft/microsoft-ui-xaml/issues/729
Bumping, though think this is a feature request, based on https://github.com/microsoft/microsoft-ui-xaml/discussions/8638
Needing this capability as well, @Scottj1s or @Sergio0694 this issue has been open for a number of years. Will this be in WASDK 1.6? If not, when can this be implemented.
Proposal: implicit DispatcherQueue support for x:Bind
Summary
Add automatic (possibly optional) dispatching to the
DispatcherQueue
instance for the current UI thread in the_BindingsTracking
type and to the necessary internal WinUI paths (eg. to deal with collection changed UI updates), specifically in thePropertyChanged
event handler and theCollectionChanged
. This would completely reverse the chain of responsability for proper thread dispatching from the viewmodel side to the UI side, and make the whole thing much more resilient and flexible. A similar concept would apply to other events handled by code within WinUI.The core idea is this: it should be responsability of an event handler to dispatch to whatever synchronization context it needs, not to the object raising the event. Specifically because if you have multiple listeners on different threads, the latter simply will never work anyway. And in general, objects raising events shouldn't need to account for who's listening to them.
Details
Handling the synchronization context for the
PropertyChanged
event in viewmodels has always been a major pain point when working with MVVM. There have been a variety of different solutions proposed, but each with their shortcomings, namely:PropertyChanged
event. Again this has two issues: for one it's not really flexible as it wouldn't work in case the same observable object is being displayed in different ways across more than a single window (where two different UI threads would be used), and the second issue is that it would inject purely platform dependent code back into a more abstract layer, i.e. the viewmodel.INotifyPropertyChanged
interface, plus again I'd argue that conceptually the UI thread dispatching should only be relegated to the actual platform dependent code. From the point of view of a .NET Standard component, individual threads should (generally) not matter much.The proposed solution is to completely flip this over and add a simple extension to the codegen for
x:Bind
(pinging @MikeHillberg about this) to allow for a more general solution to this issue, built right into the framework itself. The advantages here would be multiple, as mentioned above as well:Implementation
Consider this simple viewmodel (not implemented, it doesn't matter here):
And this XAML snippet:
If we build this and go to inspect the generated
MainPage.g.cs
file, we'll find a number of classes with various responsabilities - from updating individual UI controls to tracking the bindings, etc. In particular, we're interested in this one:This is the type that actually subscribes to the
PropertyChanged
event in our viewmodel and goes about updating the UI components. This is the only part that should need to care about the "UI thread", and this is the only part that should include the code to automatically deal with this for the user, both because it'd make all the rest of the code much simpler, and also because injecting the change here would be pretty efficient and with a small code change required.In particular, the issue is when the
PropertyChanged_ViewModel
handler is invoked, since that could be done from an other thread if thePropertyChanged
event was raised on another thread. To fix this, I propose the following:Here's the git diff:
Now, this is just a proof of concept, but hopefully it illustrates the concept well enough 😄
Rationale
Scope
x:Bind
codegen to handle the UI thread dispatchCollectionChanged
)