I have a child form in my application. This form has got about more than 50 comboboxes and everyone is getting data from database. All combobexs are loaded in the load event of the form. The data is large. Data retrieval takes about 2 minutes. when I open this form, my whole application becomes unresponsive. The application hangs and it gets life after about 2 minutes :/
As I have studied, we can use different threads in order to avoid such situations. Can someone guide, is it possible, safe and secure to implement multi-threading in order to make my application responsive?
Please guide me and write a sample code if possible how multithreading works in c#. You can simply explain using a form having a gridview that takes datatable as daTASOURCE in a separate thread and GUI is responsive even database takes too much time...Any help is appreciated.Thanx in advance!
Take a look at the BackgroundWorker class. This can do exactly what you want. You can also include something like a progress bar to show users the data is still being loaded before they go ahead and do stuff in your child form.
Use task parallel library, which is included in .NET starting from version 4 or Parallel Extensions. Samples of using TPL you can find here
And read more about it here.:
http://bradwilson.typepad.com/blog/2012/04/tpl-and-servers-pt1.html
http://www.codeproject.com/Articles/30975/Parallel-Extensions-for-the-NET-Framework-Part-I-I
http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
http://thenewtechie.wordpress.com/2012/01/03/introduction-to-tpl-part-1/
Reactive Exensions are a little bit harder. But anyway good. Samples here.
Some introduction to it here:
http://www.codeproject.com/Articles/47498/A-quick-look-at-the-Reactive-Extensions-Rx-for-Net
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2010/08/18/reactive-extensions-for-net-stuff-happens.aspx
Anyway you can find very easy more information.
Speaking about BackgroundWorker. It's good solution for winforms. But this approach is outdated. TPL or Rx are new approaches, more perfomant, more comfortable, especial when you have to much controls. Having so much controls with async operation is also a question to UI design, maybe it should be changed. Anyway BackgroundWorker also a good choice and it's up to you what select.
Related
I have made a rather complex .NET 4.0 (C#) Windows Forms application using Visual Studio 2013. The question is quite general though, and should be applicable for other versions of .NET and VS as well.
On startup the system reads config file, parses file folders and reads file content, reads data from database, performs a web request and adds data to a lot of controls on the main startup form.
I want to avoid having a splash screen with "waiting-hourglass", the goal is to make the application startup fast and show the main form immediately.
My solution has been to use backgroundworker for some of the startup tasks, making the application visible and responsive while data are fetched. The user can then choose to navigate away from the startup form and start doing other tasks without having to wait for all the startup procedures to be completed.
Is use of backgroundworker suitable for this?
What other methods should be considered instead of, or in addition to, backgroundworker to enable fast startup for an application with a lot of startup procedures?
In my applications I use a splash screen. However, I do not show a waiting-hourglass. Instead it shows a status line where current action is written, e.g. "Read config file", "Connect to database", "Perform web request", etc.
Of course, the application does not start faster but the user does not have the feeling of a hanging program and it appears faster.
In any case it depends if early access availablity makes sense for the user. A good way would also be to just preload the first page / form / tab before the user can see the interface (Splashscreen or loading bar before that).
When the first bits are loaded you could asynchroniously cache more data and only allow the user switching pages / tabs when the caching of these components is completed (you will have to display a "still loading" message or grey out other tabs while doing this to not confuse the user).
You can also just load addditional data if the user chooses to use the page / tab / feature to reduce loading unneccesary information but this will lead to waiting while using the application - it`s up to you.
Technically, as BackgroundWorker is explicitly labeled as obsolete in .NET 4.5 you should see if the introduced await/async would be a more elegant solution for you (See MSDN Asynchronous Programming with Async and Await Introduction)
MSDN says:
The async-based approach to asynchronous programming is preferable to
existing approaches in almost every case. In particular, this approach
is better than BackgroundWorker for IO-bound operations because the
code is simpler and you don't have to guard against race conditions.
See a comparison thread Background Worker vs Await/Async
See a well commented example of backgroundworker code to load GUI data if you choose to use that technique
Rather an advice than an answer:
Is use of backgroundworker suitable for this? - yes.
What other methods should be considered instead of, or in addition to, backgroundworker to enable fast startup for an application with a lot of startup procedures? - consider on-demand a.k.a. lazy loading of data. That is, load the data only when they are actually needed rather than query everything at once possibly many of them without ever being used or looked at. If this is not possible as of your UI setup, consider refining your UI and rethink whether everything should be displayed as is. For example, use separate windows or expanders to display details and query the data when they are made visible. This does not only save you time on app startup but also makes sure that you display any data in an up-to-date manner.
I have Windows Form that I use for a trading application, which, of necessity, has to display a large amount of information updating very rapidly (4 times per second).
The Windows Form I'm using has lots of controls (over 150 buttons and textboxes), and 6 datagridviews with multiple rows to display the information.
I have using different threads to perform the time-consuming operations (HTTPRequests, and various mathematical operations), but I am still finding that the GUI feels sluggish. I've noticed, in particular, that when I add more controls to the Form, things slow down, even though these extra controls are really 'doing' anything.
Can anyone explain why the mere presence of extra controls should make the GUI less responsive and/or recommend a completely different approach? Maybe I shouldn't be using Windows Forms?
Thanks.
It is hard to say something concrete without knowing your code.
A few generic ideas:
From your description, it sounds to me, like your application is very busy with repainting all the controls. Try experimenting with SuspendLayout() and ResumeLayout() and Invalidate() only those Controls that really need repainting.
Check if DoubleBuffering is enabled on both the Form(s) and ChildControls, it should be activated for most controls by default. But make sure you have it on.
Depending on your used .NET Frameworkversion check if you can use async/ await features for keeping the responiveness up.
See article MSDN Magazine article "Give Your .NET-based Application a Fast and Responsive UI with Multiple Threads". This one is a few days old, but still absolutely valid.
Some events are fired more often than you expect or need. Check those events that cause repainting of controls (i.e. this will be where you add values to be displayed to the user) if these fire too often.
Your controls take a lot of memory and I wonder why you have so many, have you considered creating controls on the fly as and when needed. Double Buffering is a must but will not help if you are clogging up memory as it is for graphic display. You need to profile your program using performance counters to find out where the problem lies, are you disposing correctly for instance?
Also are you using too many threads? Are you using the thread pool, if not you should be!
Are your controls loaded with data?
I will think some more but profiling is what you need to do next.
I currently use DevExpress controls heavily in an application. The controls are great and speed-up development time dramatically (and hence, I wouldn't want to ditch them) however, I have a few issues with their performance.
My application is a Shell/Modules/Views&ViewModels application (it follows a lot of the design patterns you would find in Prism).
When a view is first loaded it takes an extremely long time to display (on some of my users PCs with slow machines we're talking 5+ seconds of just hanging there). The time it takes apparently depends on the usage of DX controls (how many ones are on there that haven't been seen before by the application).
When you destroy the view and re-open it, it opens in less than a second. The ViewModel in my test cases/performance profiles has been made to re-create each time - so there is no shared state within my code between invocations of the view (no singleton injected objects).
After a bit of discussion and research I appear to have narrowed down the problem to on-demand loading of the template files for the DX controls.
There is a thread here about that:
http://www.devexpress.com/Support/Center/Issues/ViewIssue.aspx?issueid=Q382256
which references:
http://www.devexpress.com/Support/Center/p/B201967.aspx & DevExpress controls for WPF load time
The solution described in these threads is to either display a loading indicator or to use a hidden window with controls on it at start-up. Neither of these options are something I'd like to do (and the hidden window option didn't appear to gain much performance when I tried a simple example, interestingly - which also suggests that I might be missing something).
What I am hoping to do is to pre-load template files that I know I'm going to need on a background thread. Is there any way I can do this in WPF? (I'm thinking this is more a general WPF thing rather than a DevExpress thing - even if it's something that needs to be implemented in the DX libraries themselves).
Any ideas for either me or the guys at DevExpress?
What you can do in the background thread is to preload all the required assemblies. Also make sure they are nged-ed. The UI controls need to be initialized from the UI thread.
We have a Client-server C# application which freezes when we create 1000 and more kind of objects in UI by using some scripts rather than creating it in UI individually.
We are using lot of event handlers for certain event, but as per my understanding all threads(UI and background) and event handlers are managing properly. Then also our client application freezes. We dont know what the exact reason behind it .
Peak time hanging application took around 16 threads. Task Manager reports it taking more than 90% CPU time.
Can any body tell me the reason behind it
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.DoEvents();
Application.Run(new Test());
}
UPDATE
How can i applay lazy loading to Treeview,Listview,and propertygrid.I have used beginupdate,endupdate,double buffering,other than these any methods??
UPDATE
what does high CPU utilization means, my application exe is hanging with 13 threads and some place i heard that if you use ThreadPriority.Lowest it will reduce CPU utilization, will it work still i dont know where to use it properly??
It sounds like you need some sort of lazy loading technique to load the controls on demand as the user scrolls down the form. Loading that many controls at once will inevitably lock the application up.
This article offers some good tips on how to improve the performance of winform apps:
Practical Tips For Boosting The Performance Of Windows Form Apps
Treeviews and Listviews are not very efficient on their own and without adding lots of logic. If you don't have time to optemise them, you may want to check out 3rd party solutions like the AMAZING open source ObjectListView.
It comes in a few flavours to handle specific situations like FastObjectListView which handles millions of records or the TreeListView to handle heirarchy!
It does take a bit of effort to master but nowhere near what it takes to make Treeviews and Listviews into.. well ObjectListViews :D
http://objectlistview.sourceforge.net
http://objectlistview.sourceforge.net/cs/recipes.html#what-flavour-of-objectlistview-do-i-want-to-use
http://objectlistview.sourceforge.net/cs/recipes.html
http://objectlistview.sourceforge.net/cs/gettingStarted.html
I've used it in a few projects myself with great success!!
Cheers,
This might be quite complex so sorry for the wordy question.
1) Im going to redesign my application now to work with multiple threads (Backgroundworkers to be precise.) I will probably be having 5 or 6 bgw's for a particular gui. My first issue is, i have one method call that a gui needs to get its "core" data. Various parts of this data is then used for various other calls to places which also forms data that is displayed on the same page as the core data. How can i process this with various background workers such that backgroundworker1 does the core data getting, backgroundworker2 uses a particular item of the core to get more data, backgroundworker3 uses some core data and so on? Thus leaving my gui and main thread in an unlocked state
2) As i said previously, the gui has to get a set of core data first and then a fair few other database calls to get the rest of the important data. As i have seen i need to get this data outside of the gui constructor so there arent such big demands when the gui is created. In a design sense, how should i construct my gui such that it has access to data that then just needs to be displayed on creation opposed to, accessed and then displayed?
I hope these arent too wordy questions? I can see already that a lot of this comes down to programme design which as a novice is quite difficuly ( in my opinion of course). Hopefully someone can advise me as to what they would do in this situation.
Thanks
This sounds like a good task for a work queue. The main idea behind this is to add a work item to the queue, and this work item will have an associated function to do work on the data. The work is typically distributed to any number of threads you specify.
Several of these exist, just google for it.
Have you had a look at the .net 4 Task Parallel Library? Task Parallel Library
Check out the area titled Creating Task Continuations almost halfway down the page.
This is an example form the linked site
Task<byte[]> getData = new Task<byte[]>(() => GetFileData());
Task<double[]> analyzeData = getData.ContinueWith(x => Analyze(x.Result));
Task<string> reportData = analyzeData.ContinueWith(y => Summarize(y.Result));
getData.Start();
System.IO.File.WriteAllText(#"C:\reportFolder\report.txt", reportData.Result);
//or...
Task<string> reportData2 = Task.Factory.StartNew(() => GetFileData())
.ContinueWith((x) => Analyze(x.Result))
.ContinueWith((y) => Summarize(y.Result));
System.IO.File.WriteAllText(#"C:\reportFolder\report.txt", reportData.Result);