title: Multithreading and ProgressBar
body: <p>Need to make an multithreading  application, which performs some activities and shows progress of <strong>all work</strong> in ProgressBar. Here is the code. Only thread named "thread - 0" makes all work. I need to distribute work between all threads.</p>
  
  <pre><code>public partial class Form1 : Form
      {
          const float maxWorkedValue = 10;
          const int threadsCount = 5;
          float totalProgress;
          int threadSleepTime = 1;
  
           object locker = new object();
          List&lt;Thread&gt; threads = new List&lt;Thread&gt;();
  
          public Form1()
          {
              InitializeComponent();
  
              prBar.Maximum =  (int)maxWorkedValue;
              prBar.Step = 1;
  
              for (int i = 0; i &lt; threadsCount; i++)
              {
                  threads.Add(new Thread(BeginCalculate) { Name = "Thread - " + i.ToString() });
                  threads[i].Start();
              }
          }
  
  
  
  
          void BeginCalculate()
          {
  
              for (int i = 0; i &lt; maxWorkedValue; i++)
              {
                  lock (locker)
                  {
                      float currentProgress = CalculateLongTask(i);
                      Update((currentProgress / maxWorkedValue) * 100, Thread.CurrentThread.Name);
                      Thread.Sleep(threadSleepTime);
                  }
              }
          }
  
  
          float CalculateLongTask(int value)
          {
              for (int i=0; i&lt;value;i++)
                  Thread.Sleep(threadSleepTime);
  
              return totalProgress++;
          }
  
          void Update(float i, string threadName)
          {
              if (InvokeRequired)
              {
                  BeginInvoke(new Action&lt;float, string&gt;(Update), new object[] { i, threadName });
                  return;
              }
              label1.Text = threadName;
              prBar.Value = (int)i;
          }
  
      }
  </code></pre>
  
  <p>UPDATE2:
  I've updated the code above. But it not resolved the problem. How to synchronize the variable "i" between different threads?  An exception (progressbar.Max) is thrown. Why?</p>
  
  <pre><code> for (int i = 0; i &lt; maxWorkedValue; i++)
          {
              lock (locker)
              {
                  float currentProgress = CalculateLongTask(i);
                  Update((currentProgress / maxWorkedValue) * 100, Thread.CurrentThread.Name);
                  Thread.Sleep(15);
              }
          }
  </code></pre>