Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive GUI using Multi-threading in C# Winforms

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!

like image 235
user2109843 Avatar asked Sep 15 '26 17:09

user2109843


2 Answers

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.

like image 93
Stefan Avatar answered Sep 17 '26 06:09

Stefan


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.

like image 21
Regfor Avatar answered Sep 17 '26 06:09

Regfor