How can I profile the latency of WPF's Dispatcher? - wpf

In the quest to keep interfaces responsive I'd like to know which tasks on the Dispatcher/message pump take too long. This includes both WPF-internals as well as stuff I push on the Dispatcher by the way of BeginInvoke().
I've already thought about wrapping BeginInvoke() to measure this for me, but this captures only my own code and I fear that it might be too much overhead.
Any ideas/suggestions?

Why not subscribe to the events in the Dispatcher.Hooks property (DispatcherHooks class).
There is an OperationPosted event and an Operationcompleted event

Related

Why WPF Dependency Prop. designed to call OnPropertyChangedCallback instead of firing event?

I'm wondering why MS decided to call OnPropertyChangedCallback instead of firing some kind of event.
Is there any rationale behind this?
To me, raising events inside OnPropertyChangedCallback seems to add more code to write, and doesn't seem to have much performance benefits.
But I'd like to know if there are some edge cases / usage benefits that I might have missed (preferably with code examples).
Thank you : )
Generally speaking MS use a convention that events should be raised by the method called OnEventName. See this article. Thanks to that every developer knows how to raise a given event and doesn't have to write his own code to do so.
It is a pretty simple code but there is no need to copy&paste it and clutter the source code. You have to remember that a given event can be raised in many places. It is true regardless if we talk about WPF, WinForms or any other technology.
By the way, I tried to find OnPropertyChangedCallback in Reference Source and I din't find it.

Scheduling UI tasks for after the visual tree has settled down

In XAML-based apps, quite often I need to manipulate on-screen elements, resize or move stuff around. The situation arises usually for very custom UI controls.
The timing of stuff loading and data-binding etc. can give rise to irritating timing issues.
Traditionally, my colleagues and I have worked around these problems by 're-dispatching' work to the UI thread so it runs later, when dependent properties are in the 'final' states.
Is there a better way to do this? What strategies have you found that work?
The LayoutUpdated event can be very noisy, fine-grained, and deregistering requires forgoing a Lambda for a method and thus not being able to access enclosed variables from the outer logic - its a bit of a 'mare.
Edit
I'll give a tangible example. A custom control draws an outline around a face when doing facial recognition, so we're talking totally custom stuff here, nothing XAML does out the box.
The image needs to be scaled and sized and the paths and geometries scaled and sized so its all in alignment.
When programmatically changing the heights and widths of elements, the impact is not immediate, its only once the UI thread is relinquished back to the XAML framework does the rendering subsystems rearrange everything.
Thus, logic that depends upon the changed values needs to run after the framework has rearranged everything, and so this work needs scheduling to occur later on the UI thread, hence resorting to dispatching. It smells.
Many events and virtuals are called at times when requisite data is not yet available. Sometimes, work needs to be done upon data arrival (i.e. property change notification) which is does not typically trigger the XAML layout events. In this case, we resort to dispatcher hacks.
What about using the Loaded event?:
Loaded += LoadedHandler;
...
private void LoadedHandler(object sender, RoutedEventArgs e)
{
// Do something here when controls have loaded
}
I discovered that in WPF, this dependency property metadata argument exists to help with the problems I'm talking about.
FrameworkPropertyMetadataOptions.AffectsRender
The enum doesn't exist in Windows Store applications, presumably since its designers think the InvalidateArrange method is a suitable alternative.
Possibly, we should be a) invalidating the arrangement within our DP change handlers b) making these arrangements over multiple passes c) tolerating incorrect layout in-between passes.
Still, the using lambdas with the dispatcher is nice since variables used in calculations can be referenced from inside the closure.

I'm in MVVM ViewModel hell

So far, I am really happy with the way things have gone in my app's transition from typical click event handlers everywhere, to complete GUI decoupling. Now I'm running into something I can't quite figure out, and it's related to a window that I want my GUI to pop up, and it needs to display information from the model.
I guess the short version of my question is, is it absolutely forbidden in MVVM to allow the model to have a reference to a ViewModel? Here's my scenario: I have a bank of LEDs that cycles through RGB values very quickly. I would like a window in my GUI to display the updated colors via databinding with a ViewModel. I have the Window + UserControl working fine with a mockup ViewModel in a test application, but now I have to put this Window into my real application.
The particular mode I'm running in one that simulates what the hardware is doing. When I command the model to cycle through the colors, it starts a thread that changes the necessary class member variables' values.
My current implementation of MVVM is basically polling all of the time. To get other LEDs to update elsewhere, I have a thread running that calls a function in the ViewModel. This updates the properties, and so the GUI automatically updates since I'm using databinding. The problem in my LED example is that simulating the color sequence is done in a thread, so if I need to have a ViewModel poll for values, it will likely be slow due to excessive locking of the LED variables.
Therefore, I'm hoping that someone can recommend another approach to this problem. So far, the only thing I could really think of is to have the Window datacontext be an LEDViewModel, and then also pass the LEDViewModel to the Model. Then when I call the RGB cycling function, it can change the necessary ViewModel properties as necessary, and I won't need to use any locking at all.
Does this make sense? Any advice would be really appreciated.
Have you tried just implementing the INotifyPropertyChanged interface on your model?
It would seem to me that this should perform well enough. When the color state changes on your model, you can fire off the PropertyChanged event, update the view model state from that notification, and have the view update via a binding on the view model.
Why not use eventing on some sort of message broker for your application?
The easiest way to do this would be to use the Messenger in MVVMFoundation: http://mvvmfoundation.codeplex.com/
An example of this would be:
public class MyHardwareModel
{
private void OnHardwareLEDChanged() // or whatever
{
SharedMessages.Messenger.NotifyColleagues(SharedMessages.LEDCHANGED);
}
}
And then in your view model, when it spins up, you register for notification of these messages while that instance of the view model is alive:
public class MyHardwareViewModel
{
public MyHardwareViewModel()
{
SharedMessages.Messenger.Register(SharedMessages.LEDCHANGED, UpdateLeds);
}
private void UpdateLeds()
{
//Update ObservableCollection here.
}
}
The message mediator/broker pattern is really useful in these situations for so much more than just this. The Messenger built into MVVMFoundation is pretty powerful... in my sample I'm using pretty generic messages, but you can sent more typed messages with parameters.
There is a similar function built into Prism / Composite Application Guidance if you are using that called the EventAggregator. It's used in a similar way.
Hope this helps.
A simple approach would be to perform the polling regularly, say every 50ms. This can be done very easily using a timer, and will be less resource consuming than constant polling from a thread. 50ms seems a reasonable interval, even if your LEDs actually cycle faster, because the user won't have the time to see the color change anyway...

Patterns used in WPF

I have been getting more involved with WPF for about a year now. A lot of things are new and sometimes it is hard to get my head wrapped around it.
At the same time I am rereading the GOF Design Patterns book.
A few times I would stop in the middle because I would realize that a certain pattern is the very one used in some WPF functionality. Whenever such a realization hits me, I feel like my understanding of the related WPF principle just took a big leap. It's kind of like an aha-effect.
I also realized that I had a much easier time understanding Prism for example because the documentation does such a great job at explaining the patterns involved.
So here is my "question" (more like an effort):
In order to help us all to understand
WPF better it would be great if anyone
who also "spotted" a design pattern in
WPF could give a short explanation.
One pretty obvious example that I found is the Routed Event:
If an event is detected by a child
control and no handler has been
specified, it passes it along to its
parent and so on until it is finally
handled or no parent is found anymore.
Lets say we have an image on a button
that is inside a StackPanel that is
inside a window. If the user clicks
the image, the event will either be
handled by it (if handling code has
been specified) or "bubble" up until
one of the controls handles it. So
each control will get a chance to
react in this order.
Image
Button
StackPanel
Window
Once a control handles it, the
bubbling will stop.
This is the short explanation, for a
more precise one consult the WPF
literature.
This kind of functionality represents
the "Chain of Responsibility
Design Pattern" which states, that if
their is a request, it gets passed
along a responsibility chain to give
each object in it a chance to handle
it. The sender of the request has no
idea who will handle it which ensures
decoupling. For a more thorough
explanation follow the link.
The purpose here is merely to show how this (seemingly old 10+ years) idea found its way into our current technology and to offer another way of looking at it.
I think this is enough for a start and hope more parallels will be collected here.
Cheers, Thorsten
I don't think it is specific for WPF but the observer design pattern seems to be the foundation on which all event handling in .Net and WPF is based.
The observer design pattern is described as "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.". In .Net with the += operator you subscribe to such a change in state. Subsequently you unsubscribe with the -= operator.
I'd say CommandBindings are pretty important and fundamental to the way I develop.
WPF Tutorial - Command Bindings and Custom Commands
MSDN Overview

WinForms multi-threaded databinding scenario, best practice?

I'm currently designing/reworking the databinding part of an application that makes heavy use of winforms databinding and updates coming from a background thread (once a second on > 100 records).
Let's assume the application is a stock trading application, where a background thread monitors for data changes and putting them onto the data objects. These objects are stored in a BindingList<> and implement INotifyPropertyChanged to propagate the changes via databinding to the winforms controls.
Additionally the data objects are currently marshalling the changes via WinformsSynchronizationContext.Send to the UI thread.
The user is able to enter some of the values in the UI, which means that some values can be changed from both sides. And the user values shouldn't be overritten by updates.
So there are several question coming to my mind:
Is there a general design-guildline how to do that (background updates in databinding)?
When and how to marshal on the UI thread?
What is the best way of the background thread to interact with
binding/data objects?
Which classes/Interfaces should be used? (BindingSource, ...)
...
The UI doesn't really know that there is a background thread, that updates the control, and as of my understanding in databinding scenarios the UI shouldn't know where the data is coming from... You can think of the background thread as something that pushes data to the UI, so I'm not sure if the backgroundworker is the option I'm searching for.
Sometimes you want to get some UI response during an operation in the data-/business object (e.g. setting the background during recalculations). Raising a propertychanged on a status property which is bound to the background isn't enough, as the control get's repainted after the calculation has finished? My idea would be to hook on the propertychanged event and call .update() on the control...
Any other ideas about that?
This is a hard problem since most “solutions” lead to lots of custom code and lots of calls to BeginInvoke() or System.ComponentModel.BackgroundWorker (which itself is just a thin wrapper over BeginInvoke).
In the past, I've also found that you soon wish to delay sending your INotifyPropertyChanged events until the data is stable. The code that handles one propriety-changed event often needs to read other proprieties. You also often have a control that needs to redraw itself whenever the state of one of many properties changes, and you don’t wan the control to redraw itself too often.
Firstly, each custom WinForms control should read all data it needs to paint itself in the PropertyChanged event handler, so it does not need to lock any data objects when it was a WM_PAINT (OnPaint) message. The control should not immediately repaint itself when it gets new data; instead, it should call Control.Invalidate(). Windows will combine the WM_PAINT messages into as few requests as possible and only send them when the UI thread has nothing else to do. This minimizes the number of redraws and the time the data objects are locked. (Standard controls mostly do this with data binding anyway)
The data objects need to record what has changed as the changes are made, then once a set of changes has been completed, “kick” the UI thread into calling the SendChangeEvents method that then calls the PropertyChanged event handler (on the UI thread) for all properties that have changed. While the SendChangeEvents() method is running, the data objects must be locked to stop the background thread(s) from updating them.
The UI thread can be “kicked” with a call to BeginInvoke whenever a set of update have bean read from the database. Often it is better to have the UI thread poll using a timer, as Windows only sends the WM_TIMER message when the UI message queue is empty, hence leading to the UI feeling more responsive.
Also consider not using data binding at all, and having the UI ask each data object “what has changed” each time the timer fires. Databinding always looks nice, but can quickly become part of the problem, rather then part of the solution.
As locking/unlock of the data-objects is a pain and may not allow the updates to be read from the database fast enough, you may wish to pass the UI thread a (virtual) copy of the data objects. Having the data object be persistent/immutable so that any changes to the data object return a new data object rather than changing the current data object can enable this.
Persistent objects sound very slow, but need not be, see this and that for some pointers. Also look at this and that on Stack Overflow.
Also have a look at retlang - Message-based concurrency in .NET. Its message batching may be useful.
(For WPF, I would have a View-Model that sets in the UI thread that was then updated in ‘batches’ from the multi-threaded model by the background thread. However, WPF is a lot better at combining data binding events then WinForms.)
Yes all the books show threaded structures and invokes etc. Which is perfectly correct etc, but it can be a pain to code, and often hard to organise so you can make decent tests for it
A UI only needs to be refreshed so many times a second, so performance is never an issue, and polling will work fine
I like to use a object graph that is being continuously updated by a pool of background threads. They check for actual changes in data values and when they notice an actual change they update a version counter on the root of the object graph (or on each main item whatever makes more sense) and updates the values
Then your foreground process can have a timer (same as UI thread by default) to fire once a second or so and check the version counter, and if it changes, locks it (to stop partial updates) and then refreshes the display
This simple technique totally isolates the UI thread from the background threads
There is an MSDN article specific on that topic. But be prepared to look at VB.NET. ;)
Additionally maybe you could use System.ComponentModel.BackgroundWorker, instead of a generic second thread, since it nicely formalize the kind of interaction with the spawned background thread you are describing. The example given in the MSDN library is pretty decent, so go look at it for a hint on how to use it.
Edit:
Please note: No marshalling is required if you use the ProgressChanged event to communicate back to the UI thread. The background thread calls ReportProgress whenever it has the need to communicate with the UI. Since it is possible to attach any object to that event there is no reason to do manual marshalling. The progress is communicated via another async operation - so there is no need to worry about neither how fast the UI can handle the progress events nor if the background thread gets interruped by waiting for the event to finish.
If you prove that the background thread is raising the progress changed event way too fast then you might want to look at Pull vs. Push models for UI updates an excellent article by Ayende.
I just fought a similar situation - badkground thread updating the UI via BeginInvokes. The background has a delay of 10ms on every loop, but down the road I ran into problems where the UI updates which sometimes get fired every time on that loop, can't keep up with teh freq of updates, and the app effectively stops working (not sure what happens- blew a stack?).
I wound up adding a flag in the object passed over the invoke, which was just a ready flag. I'd set this to false before calling the invoke, and then the bg thread would do no more ui updates until this flag is toggled back to true. The UI thread would do it's screen updates etc, and then set this var to true.
This allowed the bg thread to keep crunching, but allowed the ui to shut off the flow until it was ready for more.
Create a new UserControl, add your control and format it (maybe dock = fill) and add a property.
now configure the property to invoke the usercontrol and update your element, each time you change the property form any thread you want!
thats my solution:
private long value;
public long Value
{
get { return this.value; }
set
{
this.value = value;
UpdateTextBox();
}
}
private delegate void Delegate();
private void UpdateTextBox()
{
if (this.InvokeRequired)
{
this.Invoke(new Delegate(UpdateTextBox), new object[] {});
}
else
{
textBox1.Text = this.value.ToString();
}
}
on my form i bind my view
viewTx.DataBindings.Add(new Binding("Value", ptx.CounterTX, "ReturnValue"));
This is a problem that I solved in Update Controls. I bring this up not to suggest you rewrite your code, but to give you some source to look at for ideas.
The technique that I used in WPF was to use Dispatcher.BeginInvoke to notify the foreground thread of a change. You can do the same thing in Winforms with Control.BeginInvoke. Unfortunately, you have to pass a reference to a Form object into your data object.
Once you do, you can pass an Action into BeginInvoke that fires PropertyChanged. For example:
_form.BeginInvoke(new Action(() => NotifyPropertyChanged(propertyName))) );
You will need to lock the properties in your data object to make them thread-safe.
This post is old but I thought I'd give options to others. It seems once you start doing async programming and Windows Forms databinding you end up with problems updating Bindingsource datasource or updating lists bound to windows forms control. I am going to try using Jeffrey Richters AsyncEnumerator class from his powerthreading tools on wintellect.
Reason:
1. His AsyncEnumerator class automatically marshals background threads to UI threads so you can update controls as you would doing Synchronous code.
2. AsyncEnumerator simplifies Async programming. It does this automatically, so you write your code in a Synchronous fashion, but the code is still running in an asynchronous fashion.
Jeffrey Richter has a video on Channel 9 MSDN, that explains AsyncEnumerator.
Wish me luck.
-R
I am late to the party but I believe this is still a valid question.
I would advise you to avoid using data binding at all and use Observable objects instead.
The reason is, data binding looks cool and when implemented the code looks good, but data binding miserably fails when there is lot os asynchronous UI update or multi-threading as in your case.
I have personally experienced this problem with asynchronous and Databinding in prod, we even didn't detect it in testing, when users started using all different scenarios things started to break down.

Resources