How to speed up .NET winforms rendering - winforms

I have a series of forms and navigate between them.
Each form has a set of controls for which I load properties from SQLite database and this is the long (about 1s) operation that doesn't give users the best feeling because the form is gradually being drawn.
I don't quite mind the delay but I'd like the form to be drawn when all data is loaded. I'd like to avoid new threads because this would result in cross-thread operation issues.
Is there any good solution apart from speeding the whole application up by caching the loaded data?

There is a simple way to speed up perceived performance of many controls, especially data intensive ones like listviews, listboxes, combo boxes etc.
Before you populate them call the BeginUpdate() method and when done call the EndUpdate(). This disables the redrawing of the control until you're done populating it with data.

Sorry. This is what threading is for. "Cross-thread operation issues" are well defined and there are common patterns for dealing with them. Just reduce the places where threads interact to a minimum (in this case, it would be a single place--after data is loaded) and it becomes trivial.
There are also some classes which make multithreading in a winforms app much easier, as they abstract away the interaction between threads. The BackgroundWorker (link to blog post about it) will perform work on another thread for you, and notifies you when its done by firing an event on the UI thread. You get the benefits of multithreading without any of the pitfalls.

I've found that loading Winform controls, like combo boxes and listboxes, load a lot faster when they are pointing to Views instead of a table itself, especially if you can limit the view to be leaner compared to the control having to look through an entire table.

Back in VB days I used LockWindowUpdate API. Since this takes a window handle, it should be usable also with WinForms. Though, never tried.

this link has some nice solution, as far as i think BackgroundWorker process should help.
http://devcomponents.com/blog/?p=361

Related

Reuse or create new View/ViewModel for MDI tool windows

In a MVVM MDI app with singleton tool windows (think of Visual Studio), the tool window contents change according to current selected document. There are 5 tool windows now and more to come.
I can either reuse or create new View and/or ViewModel for each tool window per each document. My question is whether there is an overwhelming reason to choose or exclude one of these options? Is there another option I totally missed?
For each tool window:
Create a new View+ViewModel per document. When the user switches document, the tool window switches View+ViewModel. The memory cost is higher with this option but perf is good.
Create a ViewModel per document but reuse View. With MVVM pattern this is doable but UI re-layout can be expensive.
Reuse both View and ViewModel to minimize memory usage. Resetting ViewModel and loading another set of data could be hard to get right.
Always go for 1, this provides better performance like you said and creates a nice separation of concern for you as develop. Since the view models stay open, you can do much more with them (such as showing a list of open documents, etc).
I ended up reusing View but not ViewModel i.e. option 2.
To answer the original question, option 3 should be excluded from consideration. Reusing VM is pointless - if the previous VM can be reused, it can as well be disposed and creating a new VM for the new data is much easier to do at a very ignorable mem/perf cost.
Option 1 vs. 2 depends on rendering complexity, performance goal and memory quota. In most cases the performance hit of switching data on the same UI should be acceptable. If the rendering really take as long as I need to save the view, there might be something wrong.

SL asynchronicity at startup... Strategies?

I'm far from new at threading and asynchronous operations, but SL seems more prone to asynchronous issues, particularly ordering of operations, than most frameworks. This is most apparent at startup when you need a few things done (e.g. identity, authorization, cache warming) before others (rendering a UI usable by your audience, presenting user-specific info, etc.).
What specific solution provides the best (or at least a good) strategy for dealing with ordering of operations at startup? To provide context, assume the UI isn't truly usable until the user's role has been determined, and assume several WCF calls need to be made before "general use".
My solutions so far involve selective enablement of UI controls until "ready" but this feels forced and overly sensitive to "readiness" conditions. This also increases coupling, which I'm not fond of (who is?).
One useful aspect of Silverlight startup to remember is that the splash xaml will continue to be displayed until the Application.RootVisual is assigned. In some situations (for example where themes are externally downloaded) it can be better to leave the assignment of the RootVisual until other outstanding async tasks have completed.
Another useful control is the BusyIndicator in the Silverlight Toolkit. Perhaps when you are ready to display some UI but haven't got data to populate the UI you assign the RootVisual using a page that has a BusyIndicator.
In my oppinion:
1st: Render start up UI that will tell the user, that the application did register his action and is runing, (Login window may be?)
2nd: Issue neccessary calls for warm up procedures in background (WCF calls and all that) and let user know about progress of tasks that are required to finish before next GUI can be made operable (main window?)
Order of operations is kind of situation specific, but please be sure to let user know what is happening if it blocks his inputs.
The selective enabling of individual controls can look interesting, but user might go for that function first and it will be disabled, so you have to make sure user knows why, or he will be confused why at start it was disabled and when he went there 10mins later it works. Also depends on what is primary function of your program and what function would that disabled control have. If application main function is showing list of books it wouldnt be nice to make that list load last.

Switching views in WPF, high level design question

So I am currently working on a UI written in WPF. One thing I really like about WPF is the way it leads you to write more decoupled, isolated UI components. One pain point for me in WPF is that it leads you to write more decoupled, isolated UI components that sometimes need to communicate with one another :). This is probably due to my relative lack of UI experience, especially in WPF (I'm not a novice, but most of my work is far more low level than UI design).
Anyway, here is the situation:
At any one time, the central area of the UI displays one of three views implemented as UserControls, let's call them Views A, B, and C.
The user will be switching between these views at various times, and there is more than one way to switch views (this works well for the customer, causes some pain in code design currently).
Right now each view switching mechanism does its own thing to transition to another view. A certain singleton class takes care of storing data and communicating between the views. I don't like this, it's messy, error prone, and the singleton class knows way too much about the details of the UI. I want to eliminate it as much as is possible.
I ran into a bug today that had to do with the timing of switching between views. To make it simple, one view needs to perform some cleanup when it is unloaded, but that cleanup erases some data that is needed for another view. If the cleanup runs after the other view is loaded, problems ensure. See what I mean? Messy.
I am trying to take a step back and imagine a different way to get these views loaded with the data they need to do their job. Some of you more experience UI / WPF people out there must have come across a similar issue. I have a couple of ideas, but I am hoping someone will present a cleaner approach to me here. I don't like depending upon order of operations (at a high level) for my code to work properly. Thanks in advance for any help you may be able to offer.
I would recommend some kind of parent ViewModel that handles the CurrentView. I wrote an example here a while back if you're interested.
Basically the parent view will have a List<ViewModelBase> AvailablePages, a ViewModelBase CurrentPage, and an ICommand ChangePageCommand
How you choose to display these is up to you. My preferred method is a ContentControl with it's Content bound to the CurrentPage, and using DataTemplates to determine which View should be displayed based on the ViewModel stored in CurrentPage
Rachel's post sums up my basic approach to this, quite well. However, I would like to add a few things based on your comments which you may want to consider here.
Note that this is all assuming a ViewModel-first approach, as mentioned in comments.
The user will be switching between these views at various times, and there is more than one way to switch views (this works well for the customer, causes some pain in code design currently).
This shouldn't cause pain in the design. The key here is to have a single, consistent way to request a "current ViewModel" change, and the View will follow suit automatically. The actual mechanism used in the View can be anything - changing the VM should be consistent.
Done correctly, there should be little pain in the design, and a lot of flexibility in terms of how the View actually operates.
Right now each view switching mechanism does its own thing to transition to another view. A certain singleton class takes care of storing data and communicating between the views. I don't like this, it's messy, error prone, and the singleton class knows way too much about the details of the UI. I want to eliminate it as much as is possible.
This is where a coordinating ViewModel can really ease things. It does not require a singleton, as it effectively "owns" the individual ViewModels of the views. One option here, that's fairly simple, is to implement an interface on the ViewModels that includes an event - the ViewModel can raise the event (which I would name based more on what the intent is, not based on the "view change"). The coordinating VM would subscribe to each child VM, and based on the event, change it's "CurrentItem" property (for the active VM) based on the appropriate content to make the request. There are no UI details at all required.
I ran into a bug today that had to do with the timing of switching between views. To make it simple, one view needs to perform some cleanup when it is unloaded, but that cleanup erases some data that is needed for another view. If the cleanup runs after the other view is loaded, problems ensure. See what I mean? Messy.
This is screaming out for a refactoring. A ViewModel should never clean up data it doesn't own. If this is occurring, it means that a VM is cleaning up data that really should be managed separately. Again, a coordinating VM could be one way to handle this, though it's very difficult without more information.
I don't like depending upon order of operations (at a high level) for my code to work properly.
This is the right way to think here. There should be no dependencies on order within your code if it can be avoided, as it will make life much simpler over time.
I am trying to take a step back and imagine a different way to get these views loaded with the data they need to do their job.
The approach Rachel and I are espousing here is effectively the same approach I used in my series on MVVM to implement the master-detail View. The nice thing here is that the "detail" portion of the View does not always have to be the same type of ViewModel or View - if you use a ContentPresenter bound to a property that's just an Object (or an interface that the VMs share), you can easily switch out the Views with completely different Views merely by changing the property value at runtime.
My suggestion for this is to have one main view model that coordinates everything (not static / singleton) that you then use sub view models to transfer data around. This keeps the decoupling you are looking for, provides testability, and allows you to control when the data for each object is changed.

WPF BackgroundWorker vs. Dispatcher

In my WPF application I need to do an async-operation then I need to update the GUI. And this thing I have to do many times in different moment with different oparations. I know two ways to do this: Dispatcher and BackgroundWorker.
Because when I will chose it will be hard for me to go back, I ask you: what is better? What are the reasons for choosing one rather than the other?
Thank you!
Pileggi
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.
BackgroundWorker on the other hand actually executes the code at the same time it is invoked, in a separate thread. It also is easier to use than true threads because it automatically synchronizes (at least I think I remember this correctly) with the main thread of an application, the one responsible for the controls and message queue (the Dispatcher thread in the case of WPF and Silverlight), so there's no need to use Dispatcher.Invoke (or Control.Invoke in WinForms) when updating controls from the background thread, although that may not be always recommended.
As Reed said, Task Parallel Library is a great alternative option.
Edit: further observations.
As I said above, the Dispatcher isn't really multithreaded; it only gives the illusion of it, because it does run delegates you pass to it at another time. I'd use the Dispatcher only when the code really only deals with the View aspect of an application - i.e. controls, pages, windows, and all that. And of course, its main use is actually triggering actions from other threads to update controls correctly or at the right time (for example, setting focus only after some control has rendered/laid-out itself completely is most easily accomplished using the Dispatcher, because in WPF rendering isn't exactly deterministic).
BackgroundWorker can make multithreaded code a lot simpler than it normally is; it's a simple concept to grasp, and most of all (if it makes sense) you can derive custom workers from it, which can be specialized classes that perform a single task asynchronously, with properties that can function as parameters, progress notification and cancellation etc. I always found BackgroundWorker a huge help (except when I had to derive from it to keep the Culture of the original thread to maintain the localization properly :P)
The most powerful, but also difficult path is to use the lowest level available, System.Threading.Thread; however it's so easy to get things wrong that it's not really recommended. Multithreaded programming is hard, that's a given. However, there's plenty of good information on it if you want to understand all the aspects: this excellent article by our good fellow Jon Skeet immediately jumps to mind (the last page of the article also has a good number of very interesting links).
In .Net 4.0 we have a different option, Task Parallel Library. I haven't worked with it much yet but from what I've seen it's impressive (and PLINQ is simply great). If you have the curiosity and resources to learn it, that's what I'd recommend (it shouldn't take that much to learn after all).
BackgroundWorker is nice if you're doing a single operation, which provides progress notifications and a completion event. However, if you're going to be running the same operation multiple times, or multiple operations, then you'll need more than one BackgroundWorker. In this case, it can get cumbersome.
If you don't need the progress events, then using the ThreadPool and Dispatcher can be simpler - especially if you're going to be doing quite a few different operations.
If C# 4 is an option, however, using the Task Parallel Library is a great option, as well. This lets you use continuation tasks setup using the current SynchronizationContext, which provides a much simpler, cleaner model in many cases. For details, see my blog post on the subject.

Global Entity Framework Context in WPF Application

I am in the middle of development of a WPF application that is using Entity Framework (.NET 3.5). It accesses the entities in several places throughout. I am worried about consistency throughout the application in regard to the entities. Should I be instancing separate contexts in my different views, or should I (and is a a good way to do this) instance a single context that can be accessed globally?
For instance, my entity model has three sections, Shipments (with child packages and further child contents), Companies/Contacts (with child addresses and telephones), and disk specs. The Shipments and EditShipment views access the DiskSpecs, and the OptionsView manages the DiskSpecs (Create, Edit, Delete). If I edit a DiskSpec, I have to have something in the ShipmentsView to retrieve the latest specs if I have separate contexts right?
If it is safe to have one overall context from which the rest of the app retrieves it's objects, then I imagine that is the way to go. If so, where would that instance be put? I am using VB.NET, but I can translate from C# pretty good. Any help would be appreciated.
I just don't want one of those applications where the user has to hit reload a dozen times in different parts of the app to get the new data.
Update:
OK so I have changed my app as follows:
All contexts are created in Using Blocks to dispose of them after they are no longer needed.
When loaded, all entities are detatched from context before it is disposed.
A new property in the MainViewModel (ContextUpdated) raises an event that all of the other ViewModels subscribe to which runs that ViewModels RefreshEntities method.
After implementing this, I started getting errors saying that an entity can only be referenced by one ChangeTracker at a time. Since I could not figure out which context was still referencing the entity (shouldn't be any context right?) I cast the object as IEntityWithChangeTracker, and set SetChangeTracker to nothing (Null).
This has let to the current problem:
When I Null the changeTracker on the Entity, and then attach it to a context, it loses it's changed state and does not get updated to the database. However if I do not null the change tracker, I can't attach. I have my own change tracking code, so that is not a problem.
My new question is, how are you supposed to do this. A good example Entity query and entity save code snipped would go a long way, cause I am beating my head in trying to get what I once thought was a simple transaction to work.
A global static context is rarely the right answer. Consider what happens if the database is reset during the execution of this application - your SQL connection is gone and all subsequent requests using the static context will fail.
Recommend you find a way to have a much shorter lifetime for your entity context - open it, do some work, dispose of it, ...
As far as putting your different objects in the same EDMX, that's almost certainly the right answer if they have any relationships between objects you'll want them in the same EDMX.
As for reloading - the user should never have to do this. Behind the scenes you can open a new context, reloading the current version of the object from the database, applying the changes they made in the UI annd then saving it back.
You might want to look at detached entities also, and beware of optimistic concurrency exceptions when you try to save changes and someone else has changed the same object in the database.
Good question, Cory. Thumb up from me.
Entity Framework gives you a free choice - you can either instanciate multiple contexts or have just one, static. It will work well in both cases and yes, both solutions are safe. The only valuable advice I can give you is: experiment with both, measure performance, delays etc and choose best one for you. It's fun, believe me :)
If this is going to be a really massive application with tons of concurrent connections I would advise using one static context or one static, core context and just few additional ones just to support the main one. But, as I wrote just few lines above - it's up to your requirements which solution is better for you.
I especially liked this part of your question:
I just don't want one of those
applications where the user has to hit
reload a dozen times in different
parts of the app to get the new data.
WPF is a really, really powerful tool and basically times when users have to press buttons to refresh data are gone forever. WPF gives you a really wide range of asynchronous, multithreading tools such as Dispatcher class or Background worker to gently refresh desired data in the background. This is really great, because not only you don't have to worry about pressing various buttons, but also background threads don't block UI, so data is refreshed transparently from user's point of view.
WPF together with Entity Framework are really worth the effort of learning - please feel free to ask if you have any further concerns.

Resources