How to make some UI task asynchronously - wpf

I have some UI task which took to long. I have some 'home made' property grid ( I uses an ItemControl , where item template uses a ContentControl, the item itself holds the datatemplate to be used in the Content control.).
The application is Shapes viewer, where each shape has its properties. each time the user clicks on some shape, the property grid shows its properties (60 different properties).
The updates process takes something about 1-2 sec. while this updating the application freeze.
Is there any way to do the updating of the property grid in the background?
Is there any way to stop last updating?
Regards, Leon

You should implement the MVVM pattern to make sure that your UI controls is a way to DISPLAY your data rather than be the HOLDER of data.
You can then choose to do various background tasks and only update VM content when ready.
Check out this video:
http://blog.lab49.com/archives/2650

you need to work with thread and dispatcher to do this.
Dispatcher in WPF/SL - http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher
In order to use another thread you have some options:
Threadpool (TaskClass only On .Net 4) - http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx
Thread class - http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
BackgroundWorker Class - http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
The 3rd option is the easiest if you don't know how to work with threads.
I guess what taking so long is the fetching the properties so what you need to do is to perform the fetch in another thread and then to use Dispatcher in this thread to update your datagrid,
you have to use Dispatcher to update your GUI from another thread.

Related

Update UI control frequently with multiple threads

I have a DevExpress GridControl oneway binding to a tableview in the viewmodel. There are about 20 background threads querying data from databases and update the tableview individually. The update to the table view is guardard with lock for async update. Dispatcher is used for refreshing the main UI thread. I also have another button to cancel the database and update functions via CancellationTokenSource.
However, when the applicatoin runs, I have to click the cancellation button many times in order to execute code in the cancel command. In another word, the UI Main thread is busy refreshing the GridControl and it blocks the Cancel Button.
Is there a way to achive this function?
Edit: Found this method helps a lot await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
It simply gives other UI controls a chance to be executed.
Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. (MSDN)
AFAIK, UI stands for User Interface, where main part is User! User is not robot, it is a person, which uses your application. You do not need to query data updates so often on UI thread. Why do you need 20 threads for database query operation? You have the single GridControl, which can show only several rows at time on the screen, 20, 50, 100 (no more). So, I suggest you to have only one thread for reading data from database, and do it once per 2-5 seconds, in order to provide User with some interactivity. For this purpose, TPL - is the good choice. Using it with CancellationToken - is good way to support cancellation with your scenario. Between database queries you can do the following:
while (true)
{
myToken.ThrowIfCancellationRequested();
// database query here
myToken.WaitHandle.WaitOne(2000)
}
Also, before updating source collection, you can use the following:
GridControl.BeginDataUpdate();
//Update your source collection
GridControl.EndDataUpdate();
This will prevent DevExpress control from listening CollectionChanged event, or any other, because on each Add/Remove action DevExpress call UpdateLayout() method, which is no so fast as we want to.
if layout is invalid in either respect, the UpdateLayout call will redo the entire layout. Therefore, you should avoid calling UpdateLayout after each incremental and minor change in the element tree.

VisualState Binding threading issue

I have an audio recording app in Windows Phone 7.
The app allows a user to play the recorded sounds.
I try to stick to MVVM guidelines where it is possible.
I have a play/stop button in a list of all recordings. Each recording has its own ViewModel, which, besides all, also controls the look of the corresponding play/stop button.
The button has a custom visual state defined in its' style.
The Visual State is bound to the ViewModel's property using the approach, shown here:
http://tdanemar.wordpress.com/2009/11/15/using-the-visualstatemanager-with-the-model-view-viewmodel-pattern-in-wpf-or-silverlight/
Having implemented this approach, whenever I want to change the look of the play/stop button, I need to set the public string property (named "PlayStopVisualState") in my ViewModel to either "PlayingState" or "Normal", and that will assign an appropriate visual state to my button.
The problem is that when user presses the play button, a SoundEffectInstance is created in a background thread, which plays the sound. The thread then waits for the playing to end. When the recording playing is over (I have to track it in the same background thread, or create another for just tracking SoundEffectInstance.State) I set the PlayStopVisualState property back to "Normal", but I get a cross-thread reference exception. Isn't MVVM specifically designed to allow developers to manipulate logical variables in a view model, and not having to worry about how the changes to them are reflected in a View?
I know that I need to do the adjustment of the PlayStopVisualState property in a Dispatcher thread in order for the problem to disappear, but this is just no right. It, from my point of view, defeats the whole purpose of MVVM, leaving only the organizational advantage.
Or am I doing something wrong? Thanks.
UPDATE:
I have worked around the problem by using
Deployment.Current.Dispatcher
but it seems to me as a very "ugly" solution, given that I almost all over have MVVM pattern followed.
Using the Dispatcher to reflect a UI-bound value is the correct way to do it, yes.
What you're forgetting is that your ViewModel is created on the UI thread. So any change to the ViewModel from a background thread, would a cross-thread operation.
You should consider if a background thread is really needed. , or if you could just schedule your action on the UI thread directly.

Can I change the Thread Affinity (Dispatcher) of a Control in WPF?

I want to create a control which takes a while to create (Pivot) and then add it to the visual tree. To do this i would need to change the dispatcher of the control (and its heirachy) before adding it to the VisualTree.
Is this possible? Are there any implications of walking the controls trees and setting the _dispatcher field via reflection?
AFAIK this only works with Freezable derived classes. The best solution I see is to create the control on the UI Thread and show a progress bar during creation. To make this possible you will have to create the control in portions an let the progress bar update itself once in a while. This not only necessary for the progressbar but also will make sure that you application does not block.
Pseudocode (execure in extra thread):
this.Dispatcher.BeginInvoke(UpdateProgress(0));
this.Dispatcher.BeginInvoke(bigControlBuilder.Build(0,25));
this.Dispatcher.BeginInvoke(UpdateProgress(25));
this.Dispatcher.BeginInvoke(bigControlBuilder.Build(25,50));
this.Dispatcher.BeginInvoke(UpdateProgress(50));
this.Dispatcher.BeginInvoke(bigControlBuilder.Build(50,75));
this.Dispatcher.BeginInvoke(UpdateProgress(75));
this.Dispatcher.BeginInvoke(bigControlBuilder.Build(75,100));
this.Dispatcher.BeginInvoke(UpdateProgress(100));
this.Dispatcher.BeginInvoke(this.Children.Add(bigControlBuilder.GetControl()));
Update:
To make complex control more responsive you could also try UI-Virtualization/Data-Virtualisation:
Only load and show those visual items of the data items that are currently visible to ther user. Do not load and show visual items that are scrolled offscreen are to small to see or are in any other way invisible to the user. Upon userinteraction unload items that become invisble, load items that become visible.
To answer your question, I suppose it is possible to set _dispatcher using reflection but I would not recommend it at all. There is a deeply ingrained notion in WPF of thread affinity and STA so I wouldn't mess with that.
bitbonk's approach is a good one.
Another approach we have used in a project of ours was to create a second UI thread and have a progress indicator be rendered by the second UI thread while the first UI thread is building the UI. As long as the progress bar stays in the visual tree owned by the second UI thread, you should be good.

WPF UI Thread Status

I have a wpf application that takes ~30 seconds to create a map/graphic. I have read there is no easy way to tie into the UI rendering thread to get a progress update. So I was going to use a counter on a value converter which colors my map but that is also on the UI Thread, so my question is has anyone found any slick methods of working with the rendering thread yet?
Thanks.
You could create your map/graphic in a BackgroundWorker which allows you to call ReportProgress in your function, where you can set your percentage of completion and raise the ProgressChanged event to update your UI.
When you say UI rendering thread, you mean that hidden rendering thread from WPF internals or UI thread?
In any case, having a separate thread that builds your map and notifies UI about progress doesn't help you?
im not sure if this is what you are looking for.
I use something similar to the code below to load in around 300 images( about 200 mb ) and have no UI slow down at all. (the user can see each image being loaded in, I just keep an empty placeholder image up till the final image is loaded)
The images are loaded in a background thread, and then the function is called to actually put them into the WPF scene.
here is a simple example using a textbox. You can call this function from any thread and it will work out if it needs to change the to the GUI thread. (for my project of course i am doing it with bitmaps, not a textbox ).
delegate void UpdateUIThreadDelegate(String str);
public void DisplayString(String strMessage)
{
if (this.InvokeRequired)
{
UpdateUIThreadDelegate updateDelegate = DisplayString;
this.BeginInvoke(updateDelegate, strMessage);
return;
}
myTextBox.Text = strMessage;
}
Cheers
Anton
If you use binding to tie your UI with a datasource which can take long time to return, you can set 'IsAsync=True' on your binding so that the binding become asynchronous.
If you want to display some other datas (even an animation I guess) during the time your datasource is loading, you can use a PriorityBinding
HTH
Riana

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