473,324 Members | 2,313 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

C# Multithreading.

Airslash
221 100+
Hello,

I'm aware that the code I'm currently using is far from perfect. I'm not even sure if it does exactly what it is supposed to do, but I'm trying to do the following:

My Resources class, loads several tables from the database inside the application. This is static data that doesn't change such as a list of Countries for example. The basic idea behind this, is to run all the queries into seperate threads to prevent the application from hanging while the data is loading. I'm using the following code for that:

Expand|Select|Wrap|Line Numbers
  1. public void Load()
  2.         {
  3.             // Configure the Progressbar.
  4.             ConfigureProgressBar();
  5.  
  6.             // Create for each method a new thread.
  7.             new Thread(new ThreadStart(LoadActivityActions)).Start();
  8.             new Thread(new ThreadStart(LoadActivityCategories)).Start();
  9.             new Thread(new ThreadStart(LoadAssignmentStatus)).Start();
  10.             new Thread(new ThreadStart(LoadCompanyStatus)).Start();
  11.             new Thread(new ThreadStart(LoadCountries)).Start();
  12.             new Thread(new ThreadStart(LoadDegrees)).Start();
  13.             new Thread(new ThreadStart(LoadExternalStatus)).Start();
  14.             new Thread(new ThreadStart(LoadIdentificationAction)).Start();
  15.             new Thread(new ThreadStart(LoadInternalStatus)).Start();
  16.             new Thread(new ThreadStart(LoadOfferStatus)).Start();
  17.             new Thread(new ThreadStart(LoadPersonCategories)).Start();
  18.             new Thread(new ThreadStart(LoadReport)).Start();
  19.             new Thread(new ThreadStart(LoadSalesStatus)).Start();
  20.             new Thread(new ThreadStart(LoadSectors)).Start();
  21.             new Thread(new ThreadStart(LoadTargetStatus)).Start();
  22.  
  23.             while (this.ProgressBar.Value != this.ProgressBar.Maximum)
  24.             {
  25.                 Thread.Sleep(0);
  26.             }
  27.         }
  28.  
So assuming the code is correct, each load function is executed in a sperate thread. The class contains also a ProgressBar. Which starts at value 0, and goes to a maximum value that is determined by running a count(*) to get the amount of rows that will be loaded. The question is, will my main thread be waiting till everything has been loade dby using that IF statement?

Or am I completly using the Thread system in a wrong way ?
Nov 23 '07 #1
10 2924
CyberSoftHari
487 Expert 256MB
You have to use
Expand|Select|Wrap|Line Numbers
  1. Thread.Sleep(<Intervel>);
method to execute your threads as you want.
Nov 23 '07 #2
Shashi Sadasivan
1,435 Expert 1GB
Hello,

I'm aware that the code I'm currently using is far from perfect. I'm not even sure if it does exactly what it is supposed to do, but I'm trying to do the following:

My Resources class, loads several tables from the database inside the application. This is static data that doesn't change such as a list of Countries for example. The basic idea behind this, is to run all the queries into seperate threads to prevent the application from hanging while the data is loading. I'm using the following code for that:

Expand|Select|Wrap|Line Numbers
  1. public void Load()
  2.         {
  3.             // Configure the Progressbar.
  4.             ConfigureProgressBar();
  5.  
  6.             // Create for each method a new thread.
  7.             new Thread(new ThreadStart(LoadActivityActions)).Start();
  8.             new Thread(new ThreadStart(LoadActivityCategories)).Start();
  9.             new Thread(new ThreadStart(LoadAssignmentStatus)).Start();
  10.             new Thread(new ThreadStart(LoadCompanyStatus)).Start();
  11.             new Thread(new ThreadStart(LoadCountries)).Start();
  12.             new Thread(new ThreadStart(LoadDegrees)).Start();
  13.             new Thread(new ThreadStart(LoadExternalStatus)).Start();
  14.             new Thread(new ThreadStart(LoadIdentificationAction)).Start();
  15.             new Thread(new ThreadStart(LoadInternalStatus)).Start();
  16.             new Thread(new ThreadStart(LoadOfferStatus)).Start();
  17.             new Thread(new ThreadStart(LoadPersonCategories)).Start();
  18.             new Thread(new ThreadStart(LoadReport)).Start();
  19.             new Thread(new ThreadStart(LoadSalesStatus)).Start();
  20.             new Thread(new ThreadStart(LoadSectors)).Start();
  21.             new Thread(new ThreadStart(LoadTargetStatus)).Start();
  22.  
  23.             while (this.ProgressBar.Value != this.ProgressBar.Maximum)
  24.             {
  25.                 Thread.Sleep(0);
  26.             }
  27.         }
  28.  
So assuming the code is correct, each load function is executed in a sperate thread. The class contains also a ProgressBar. Which starts at value 0, and goes to a maximum value that is determined by running a count(*) to get the amount of rows that will be loaded. The question is, will my main thread be waiting till everything has been loade dby using that IF statement?

Or am I completly using the Thread system in a wrong way ?
Hi,
your threads will be loaded,
The executer will start all the threads and go to the if statement where it will keep looping until yoour condition is reached (which is governed by the threads i beilive).

The procedure is fine, its good to use threads for this as certain things may take more time to load and you dont want to wait for it if another component could have been loaded.

it looks good. dosent seem to have any problem
Nov 23 '07 #3
Airslash
221 100+
That was the anwser I was looking for :)
I will definitly give the code a go, and post feedback in this topic whether or not it runs smooth or not.
Nov 23 '07 #4
Airslash
221 100+
OK,

I have been fiddling with the class I wrote. And now it contains several methods to load information from a table in the database. Each of these methods also contains the following piece of code :

Expand|Select|Wrap|Line Numbers
  1. if (null != this.ProgressBar)
  2. {
  3.        this.ProgressBar.Increment(1);
  4. }
  5.  
So I try to increase the value of my progressbar (which is located on a form) by 1 each time the method has created a new object. Picture this as 6 methods running in 6 seperate threads, and each method creating over 10 objects.

The problem now is that I'm getting Exception errors that don't allow me to to increase the value of my progress bar because its located on the form and not part of the actuall thread.

I've been reading on forums and the internet, and they mention delegates. Am I supposed to let my threads call a delegate that does the actuall updating ?
Nov 27 '07 #5
CyberSoftHari
487 Expert 256MB
Increase the progress bar value in methods which is going to run in thread.
But that is not a proper solution.
Why you are using invert validation?
Expand|Select|Wrap|Line Numbers
  1. null != this.ProgressBar
Nov 27 '07 #6
Airslash
221 100+
Increase the progress bar value in methods which is going to run in thread.
But that is not a proper solution.
Why you are using invert validation?
Expand|Select|Wrap|Line Numbers
  1. null != this.ProgressBar
That came to my mind, but I have worked around it now. My preloader class ontains a delegate which will call a function in the Form. This function will create a new Delegate on itself and will use the Invoke() method to execute this. My progressbar now updates very smoothly without Thread violations.

I'm using Invert checks in everything. I always want to have the value I compare against first, and the method or property producing the value as second part.

Just my coding standard.
Nov 27 '07 #7
CyberSoftHari
487 Expert 256MB
Can you able to post that part of code? (That will be helpful for experts to guide you.)
Nov 27 '07 #8
Airslash
221 100+
Current problem : Application suddenly terminates
Suspected Reason : Infinite Loop

Login Form
Basicly this snippet of code comes from my ok button on the login form. It creates the preloader form, and removes the current form.
Expand|Select|Wrap|Line Numbers
  1. // The login was succesfull. We can now create the preloader form.
  2. frmPreloader f = new frmPreloader(connectionstring);
  3. f.Show();
  4. this.Dispose();
  5.  
Preloader Form
This is a form with a progressbar on it called 'progressbar', and a button to continue with the application called 'btncontinue'.

Code for my Load Event
Expand|Select|Wrap|Line Numbers
  1. private void frmPreloader_Load(object sender, EventArgs e)
  2. {
  3.             // Create a new instance of the Resources class.
  4.             Resources myResource = Resources.Instance(this.Connectionstring);
  5.  
  6.             // Set which function should be called when the load methods need to update.
  7.             myResource.UpdateProgressBar += new Resources.UpdateProgressBarHandler(IncrementbarEvent);
  8.  
  9.             // Configure the progressbar.
  10.             this.progressbar.Minimum = 0;
  11.             this.progressbar.Value = 0;
  12.             this.progressbar.Maximum = myResource.CountMaxValue();
  13.  
  14.             // Preload all the data.
  15.             new Thread(new ThreadStart(myResource.Load)).Start();
  16. }
  17.  
The code I use to increment the progressbar.
Expand|Select|Wrap|Line Numbers
  1. private void IncrementbarEvent()
  2.         {
  3.             // Tell what to execute to edit the progressbar.
  4.             CallIncrement func = new CallIncrement(Increment);
  5.  
  6.             // Invoke the method. Invoke is required to remain in a safe
  7.             // multithreading environment.
  8.             if (this.InvokeRequired == true)
  9.             {
  10.                 Invoke(func);
  11.             }
  12.             else
  13.             {
  14.                 Increment();
  15.             }
  16.         }
  17.  
  18.         private void Increment()
  19.         {
  20.             this.progressbar.Increment(1);
  21.  
  22.             if (this.progressbar.Value == this.progressbar.Maximum)
  23.             {
  24.                 this.btncontinue.Enabled = true;
  25.             }
  26.         }
  27.  
As last section we have the Resources class that does the actuall preloading.
This class is used by calling the Load() method, as shown in the code above. The Load method from the form calls the Load method of my class.

This load method on its own calls another series of methods in seperate threads that start by collecting information from the database and store it in lists. This class is a singleton implementation meaning that the information should be staying inside the memory.

Below is a piece of such a Load method that shows how the objects are beeing contructed inside these methods. It wil also show how I use my delegate to switch back to my preloader form to update the progressbar by calling the UpdateProgressBar() event from my resources class. (which is a delegate pointing back at the form.)

Expand|Select|Wrap|Line Numbers
  1.  private void LoadCountries() 
  2.         {
  3.             // Create the string to retrieve the information.
  4.             string query = "SELECT ID, Name FROM Countries ORDER BY Name";
  5.  
  6.             // Get the actuall SqlDataReader.
  7.             SqlDataReader reader = SqlHelper.ExecuteReader(this.Connectionstring, CommandType.Text, query);
  8.  
  9.             // Check if the SqlDataReader has been properly initialized.
  10.             if (null != reader && true == reader.HasRows)
  11.             {
  12.                 // Create a new List.
  13.                 this._countries = new List<Country>();
  14.  
  15.                 // Iterate through the SqlDataReader
  16.                 while (true == reader.Read())
  17.                 {
  18.                     // Create a new Country object.
  19.                     Country obj = new Country(CastDBNull.To<int>(reader["ID"], 0), CastDBNull.To<string>(reader["Name"], String.Empty));
  20.  
  21.                     // Add the object to the List.
  22.                     this._countries.Add(obj);
  23.  
  24.                     // Increment the progressbar.
  25.                     UpdateProgressBar();
  26.                 }
  27.             }
  28.  
  29.             // Close the SqlDataReader.
  30.             if (null != reader)
  31.             {
  32.                 reader.Close();
  33.             }
  34.         }
  35.  
Nov 27 '07 #9
Airslash
221 100+
UPDATE:

Ok appaerently its the this.dispose() in my login form thats causing this all mess.

If I replace the this.dispose() in the ok button event, by this.Hide() the preloader works perfectly.

so my guess now is that because i use Application(new frmlogin()) in my program.Cs file, it kills everything....
Nov 27 '07 #10
Airslash
221 100+
Final Update:

moved everything to seperate threads beeing called from a main thread including the login. Application flies and works like a charm now
Nov 28 '07 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: dixp | last post by:
I'm new to writing multithreaded apps and I have a design question. I have a winforms app and a class which has a method that does processing which is time intensive. I want the user to be able...
47
by: mihai | last post by:
What does the standard say about those two? Is any assurance that the use of STL is thread safe? Have a nice day, Mihai.
16
by: Robert Zurer | last post by:
Can anyone suggest the best book or part of a book on this subject. I'm looking for an in-depth treatment with examples in C# TIA Robert Zurer robert@zurer.com
5
by: sarge | last post by:
I would like to know how to perform simple multithreading. I had created a simple form to test out if I was multithreading properly, but got buggy results. Sometime the whole thig would lock up...
9
by: tommy | last post by:
hi, i have found a example for multithreading and asp.net http://www.fawcette.com/vsm/2002_11/magazine/features/chester/ i want to speed up my website ... if my website is starting, they...
2
by: Rich | last post by:
Hello, I have set up a multithreading routine in a Test VB.net proj, and it appears to be working OK in debug mode and I am not using synchronization. Multithreading is a new thing for me, and...
55
by: Sam | last post by:
Hi, I have a serious issue using multithreading. A sample application showing my issue can be downloaded here: http://graphicsxp.free.fr/WindowsApplication11.zip The problem is that I need to...
5
by: sandy82 | last post by:
Whats actuallly multithreading is ... and how threading and multithreading differ . Can any1 guide how multithreading is used on the Web .. i mean a practical scenario in which u use...
2
by: Pradnya Patil | last post by:
hi , I am trying to draw ' html div-tag ' on the screen which will resemble a rectangle through vb.net code. I want it to be drawn faster...so I introduced multithreading using Threadpool. I...
7
by: Ray | last post by:
Hello, Greetings! I'm looking for a solid C++ multithreading book. Can you recommend one? I don't think I've seen a multithreading C++ book that everybody thinks is good (like Effective C++ or...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.