There was an error in this gadget

Search This Blog

Progressbar with multi-threading in c#

Any process is running but if we dont know how long it will take, then its very frustrating to sit and wait for the process to complete. So to overcome this problem we have PROGRESSBAR.
This control in C# helps us to identify how long the process is going to take.

ProgressBar is an inbuilt control with visual studio 2005 and 2008.

To learn more about progressbar please visit http://www.java2s.com/Tutorial/CSharp/0460__GUI-Windows-Forms/ProgressBarPerformStep.htm because in this article we are going to learn about how to show progress when any background process is going on, i.e use of progressbar with multi-threading.

Threading is very useful concept. User dont like to sit idle after processing one task which takes long time. So here comes threading in picture, user executes a process and then back to important work, while the executed work goes on with the help of threading. Visit http://www.albahari.com/threading/ to get more info on threading.

Sometimes there is a need to show progress of the backround threads processing. So here is the code which helps to show the progressbar for multiple-processes executing at once(multi-threading)

Here I have written code in C# and form based application.

First declare a delegate and Progress Counter.

private delegateUpdateProgressBar updateProgressBar;
int Progress=0;

Then create its instance in the constructor of the form

public Form1()

{
    InitializeComponent();
    updateProgressBar = new delegateUpdateProgressBar(UpdateProgressBar);
}

Lets have progressbar control with name = progressBar1
Now create multiple threads on button click

protected void button1_click(object sender, EventArgs e)
{
   progressBar1.Maximum = 1000;// this can vary, depending upon number of records to be processed.

   progressBar1.Value = 1;
   int ThreadCount = 10 // for testing. you can change according to your requirements
   List<Thread> th = new List<Thread>();

   for (int i = 0; i < ThreadCount; i++)
   {
      Thread t = new Thread(ExecuteThreadExample);//this is the function which will execute parrallely
      th.Add(t);
   }
   foreach (Thread t in th)
  {
      t.Start();
   }
}

private void ExecuteThreadExample()
{
   for(int k=0;k<=100;k++)
   {
        UpdateProgress();
   }
}

private void UpdateProgress()
{
    Progress++;
    Invoke(updateProgressBar, Progress);
}

private void UpdateProgressBar(int iValue)
{
    progressBar1.Value = iValue;
}


Below is the image of the progressbar.


Progressbar
Progressbar


4 comments: