Methods to update GUI in WPF - c#

I would like to ask what method to update GUI is better for my scenario.
I would like to manipulate (move) multiple controls from point to point based on the input from user's touches.
I know a few difference way to do it.
Dispatcher Timer & Timer. (What's the difference between them?)
BackgroundWorker.
Storyboard & BeginAnimation Method.
Which of these method is generally recommended to use in term of memory and resource saving and simpler to code?
Thank you!

I suppose these 3 SO QA should help u understand all the differences:
DispatcherTimer vs a regular Timer in WPF app for a task scheduler
Comparing Timer with DispatcherTimer
WPF BackgroundWorker vs. Dispatcher

Apart from the link given by Vijay, a common concept that is vital in WPF application while you manipulate visuals is Dispatcher
In short, a Dispatcher is a message queue gateway manager to the UI, that receives delegates and prioritises them to execute on the given thread. In WPF, UI thread is STA. Also any visual created on UI thread has a thread affinity which means if you are performing any multi threaded functionality (for faster performance) then when it comes to manipulating those visuals such as updating their values, increasing / deacresing their size, focusing them, transforming them etc. has to be done using the UI Dispatcher.
Now back to your situation, when you want to move items, translate transform animation is a good option.
Hope this helps you in correct direction.

Related

How to see how much prossesing time a C# Windows Forms application needs?

I have a C# Windows Forms application wicht does some camera control and computer vision. For all the parts which take longer for calculation I used seperate threads. But there are still some parts which are in the callback functions of the GUI. As I understand, all these callback functions are executed in the same thread. Is there a way to see how much time this thread is working or idle? What percentage of idle time is needed such that the GUI is still responsive?
It's recommended that you shouldn't block the UI thread for more than 50ms, otherwise it will affect the UI responsiveness. I.e., two UI callbacks queued with Form.BeginInvoke, each taking ~50ms to complete, may introduce some unpleasant UI experience to the user.
It doesn't make sense to update the UI more often than the user can react to it (i.e, ~24 frames per second). So, you should throttle the UI thread callbacks and give user input events a priority.
I recently posted an example of how it can possibly be done:
https://stackoverflow.com/a/21654436/1768303
For simple tasks you could use a stopwatch and measure the time manually. However I think you'll need to check what a performance profiler is.
Also - there is little situations in which your GUI needs that heavy processing. In most cases the problem comes from putting too much calculations in event handlers instead of implementing them somewhere outside and then update the form when finished. It's less of a single/multi-threading problem and more of using available events properly.

Is there an alternative to use the Background Worker in WPF?

I am a beginner with WPF, in my application I need to perform a series of Initialization steps, these take 10-15 seconds to complete during which my UI becomes unresponsive.
I was using yesterday the background worker but it didn't update my window, in fact it was frozen. Not sure, but maybe it didn't work because this control is only for Windows Forms.
UPDATE:
If not too much trouble, can you post me an example to use the alternative? For my case, the program will get some values from a database in a blucle.
Dispatcher.
The Dispatcher maintains a prioritized queue of work items for a specific thread. This might help you for updating your UI. If you have a lot of UI related initializations even this won't be able to help you much.
Dispatcher is not always an alternative to BackgroundWorker actually. The best practice is to select the more appropriate one as per your requirement. For example if you want something to execute without queuing BackgroundWorker is the solution. On the other hand if queuing is not a problem then Dispatcher is an alternative. For example, Dispatcher is using in Spell checkers and syntax highlighting functionality.
WPF Thread Model
All WPF applications start out with two important threads, one for
rendering and one for managing the user interface. The rendering
thread is a hidden thread that runs in the background, so the only
thread that you ordinarily deal with is the UI thread. WPF requires
that most of its objects be tied to the UI thread. This is known as
thread affinity, meaning you can only use a WPF object on the thread
on which it was created. Using it on other threads will cause a
runtime exception to be thrown. Note that the WPF threading model
interoperates well with Win32®-based APIs. This means that WPF can
host or be hosted by any HWND-based API (Windows Forms, Visual Basic®,
MFC, or even Win32).
The thread affinity is handled by the Dispatcher
class, a prioritized message loop for WPF applications. Typically your
WPF projects have a single Dispatcher object (and therefore a single
UI thread) that all user interface work is channeled through.
NOTE :
The main difference between the Dispatcher and other threading methods
is that the Dispatcher is not actually multi-threaded. The Dispatcher
governs the controls, which need a single thread to function properly;
the BeginInvoke method of the Dispatcher queues events for later
execution (depending on priority etc.), but still on the same thread.
See this thread for more information.
You could also queue items up with the thread pool and run the tasks like that, but be careful, if your tasks need to update the UI when they are finished you will have to marshal the data back to the UI thread.
One could use asynchronous delegates.
http://msdn.microsoft.com/en-us/library/ms228963.aspx
Just make sure if you are doing any UI related updates use:
Dispatcher.CheckAccess()
Here a simple example:
private void HandleUIButtons()
{
if (!btnSplit.Dispatcher.CheckAccess())
{
//if here - we are on a different non-UI thread
btnSplit.Dispatcher.BeginInvoke(new Action(HandleUIButtons));
}
else
{
btnSplit.IsEnabled = true; //this is ultimately run on the UI-thread
}
}
Taken from here:
http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces.html

Timers and multithreading

I have a question about timers and threads. I noticed that the timers misbehaving when started within the threads, while the timers are part of the Winform.
Generally I'm interested in problems related threads and timers.
Happy New Year to you all, the answers may be to wait until 2011:)
Sounds like you're using a System.Threading.Timer and using a TimerCallback that performs GUI updates. Is that it?
There are a number of correct ways to deal with this. Use a System.Windows.Forms.Timer and handle its Tick event if you're looking to update the UI. Use a BackgroundWorker, do non-UI work in its DoWork event and then perform UI updates in its RunWorkerCompleted event if you're performing long-running background tasks.
In general, the important thing to understand about multithreading as it pertains to Windows Forms is this: all Windows Forms application have a UI thread, which is the only thread that is allowed to perform UI updates. It is continually processing a queue onto which user actions are pushed and handle via events. When you try to do anything that updates a UI control from any thread besides this thread, you get an exception because this behavior was not planned for in the design of Windows Forms components, and would therefore very likely cause bugs or possibly crash the entire application.
So the approach to multithreading is generally to separate work into two parts, that which can be done in the background (on a non-UI thread) and that which must sent to the queue being processed by the UI thread so that it can be handled in a safe manner. The usefulness of types like System.Windows.Forms.Timer and BackgroundWorker is that they encapsulate many of the difficult details of this process for you, allowing you to focus on the code you want to run.
That's a high level view of how multithreading works with Windows Forms. I'm sure others can provide plenty of references pointing you to more information on the subject (and if nobody else does, maybe I can look some up later).
Comparing the Timer Classes in the .NET Framework Class Library is a good article to read.
Google maybe?
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

Pattern for periodically updating screen data

I am new to the world of GUI programming and I am writing a little GUI app using IronPython and WinForms. It reads values from an external device and displays them in a ListView component (name, value). I want to periodically perform the reading and updating of the ListView component at a certain fixed rate.
I had the following ideas to accomplish this:
A timer, which periodically triggers the read/screen update directly in the OnTick handler
A timer, whose OnTick handler triggers a BackgroundWorker to perform the read/update
Since the first solution will block the GUI until the read/update loop is done, which, depending on the number of values being read from the device, could take some time, I think the BackgroundWorker might be a better solution. I might want to add some functionality to manipulate the ListView items later (add, remove values etc.) and a blocked GUI does not seem like a good idea.
Is there a certain design pattern or a better way to accomplish reading/updating screen data?
NOTE: Any code examples can be IronPython or C#. The conversion from C# to IronPython is pretty straight forward. Thanks!
Personally, I'd have one thread that's responsible for reading values out of the device and storing the data in a data structure, and then a System.Windows.Forms.Timer (there's 3 Timers in .NET, this is the only one that ticks in the thread that's safe to update your controls) to read values out of that data structure and update the UI. You may need to synchronise that data structure, you may not.
That way the device can take as long as it likes to return data, or it can push as many millions of rows per second at you, and the UI thread will still poll at your predetermined tick rate (probably every 100 msec?). Since your timer ticks are just reading data out of memory, the UI won't block for IO.
The BackgroundWorker is prefered when you have lot of work to do in the background.
Use a Timer to trigger a function that will do the necessary work in a second thread.
It won't block the UI. (don't forget to update the controls on the UI thread).
System.Threading.Thread newThread;
newThread = new System.Threading.Thread(anObject.AMethod);
http://msdn.microsoft.com/fr-fr/library/ms173178(VS.80).aspx
Another option rather than getting the Timer and the Background worker thread working would be to use the System.Threading.Timer, this will execute your method on a thread on a regular interval and once you have the data you can use Control.Invoke or Control.BeginInvoke to update the control in the UI thread.

Multithreading on Windows Forms

I want to paralelize a 3D voxel editor built on top of Windows Forms, it uses a raycaster to render so dividing the screen and getting each thread on a pool to render a part of it should be trivial.
The problem arises in that Windows Forms' thread must run as STA - I can get other threads to start and do the work but blocking the main thread while waiting for them to finish causes strange random deadlocks as expected.
Keeping the main thread unblocked would also be a problem - if, for example, the user uses a floodfill tool the input would be processed during the rendering process which would cause "in-between" images (an object partially colored, for example). Copying the entire image before every frame isn't doable either because the volumes are big enough to offset any performance gain if it has to be copied every frame.
I want to know if there is any workaround to get the amin thread to appear blocked to the user in a way that it will not be actually blocked but will delay the processing of input till the next frame.
If it isn't possible, is there a better design for dealing with this?
EDIT: Reading the anwsers I think I wasn't clear that the raycaster runs in real time, so showing progress dialogs won't work at all. Unfortunately the FPS is low enough (5-40 depending on various factors) for the input between frames to produce unwanted results.
I have already tried to implement it blocking the UI thread and using some threads of a ThreadPool to process and it works fine except for this problem with STA.
This is a common problem. With windows forms you can have only one UI thread. Don't run your algorithm on the UI thread because then the UI will appear frozen.
I recommend running your algorithm and waiting for it to finish before updating the UI. A class called BackgroundWorker comes pre-built to do just this very thing.
Edit:
Another fact about the UI thread is that it handles all of the mouse and keyboard events, along with system messages that are sent to the window. (Winforms is really just Win32 surrounded by a nice API.) You cannot have a stable application if the UI thread is saturated.
On the other hand, if you start several other threads and try to draw directly on the screen with them, you may have two problems:
You're not supposed to draw on the UI with any thread but the UI thread. Windows controls are not thread safe.
If you have a lot of threads, context switching between them may kill your performance.
Note that you (and I) shouldn't claim a performance problem until it has been measured. You could try drawing a frame in memory and swapping it in at an appropriate time. Its called double-buffering and is very common in Win32 drawing code to avoid screen flicker.
I honestly don't know if this is feasible with your target frame rate, or if you should consider a more graphics-centered library like OpenGL.
Am I missing something or can you just set your render control (and any other controls that generate input events) to disabled while you're rendering a frame? That will prevent unwanted inputs.
If you still want to accept events while you're rendering but don't want to apply them until the next frame, you should leave your controls enabled and post the detail of the event to an input queue. That queue should then be processed at the start of every frame.
This has the affect that the user can still click buttons and interact with the UI (the GUI thread does not block) and those events are not visible to the renderer until the start of the next frame. At 5 FPS, the user should see their events are processed within 400ms worst case (2 frames), which isn't quite fast enough, but better than threading deadlocks.
Perhaps something like this:
Public InputQueue<InputEvent> = new Queue<InputEvent>();
// An input event handler.
private void btnDoSomething_Click(object sender, EventArgs e)
{
lock(InputQueue)
{
InputQueue.Enqueue(new DoSomethingInputEvent());
}
}
// Your render method (executing in a background thread).
private void RenderNextFrame()
{
Queue<InputEvent> inputEvents = new Queue<InputEvent>();
lock(InputQueue)
{
inputEvents.Enqueue(InputQueue.Dequeue());
}
// Process your input events from the local inputEvents queue.
....
// Now do your render based on those events.
....
}
Oh, and do your rendering on a background thread. Your UI thread is precious, it should only do the most trivial work. Matt Brundell's suggestion of BackgroundWorker has lots of merit. If it doesn't do what you want, the ThreadPool is also useful (and simpler). More powerful (and complex) alternatives are the CCR or the Task Parallel Library.
Show a modal "Please Wait" dialog using ShowDialog, then close it once your rendering is finished.
This will prevent the user from interacting with the form while still allowing you to Invoke to the UI thread (which is presumably your problem).
If you don't want all the features offered by the BackgroundWorker you can simply use the ThreadPool.QueueUserWorkItem to add something to the thread pool and use a background thread. It would be easy to show some kind of progress while the background thread was performing it's operations as you can provide a delegate callback to notify you whenever a particular background thread is done. Take a look at ThreadPool.QueueUserWorkItem Method (WaitCallback, Object) to see what I'm referring you to. If you need something more complex you could always use the APM async method to perform your operations as well.
Either way I hope this helps.
EDIT:
Notify user somehow that changes are being made to the UI.
On a(many) background threads using the ThreadPool perform the ops you need to perform to the UI.
For each operation keep a reference to the state for the operation so that you know when it completed in the WaitCallback. Maybe put them in some type of hash / collection to keep ref to them.
Whenever an operation completes remove it from the collection that contains a ref to the ops that were performed.
Once all operations have completed (hash / collection) has no more references in it render the UI with the changes applied. Or possibly incrementally update the UI
I'm thinking that if you are making so many updates to the UI while you are performing your operations that is what is causing your problems. That's also why I recommended the use of SuspendLayout, PerformLayout as you may have been performing so many updates to the UI the main thread was getting overwhelmed.
I am no expert on threading though, just trying to think it through myself. Hope this helps.
Copying the entire image before every frame isn't doable either because the volumes are big enough to offset any performance gain if it has to be copied every frame.
Then don't copy the off-screen buffer on every frame.

Categories