title: Updating UI from a background thread which is called in a loop in main UI when the thread finishes
body: <p>I have a WinForms application that is calling a business class method that performs some heavy duty action taking about 5 seconds for each call. The main form calls this method in a loop. This loop can run from 10 times to maybe up to 10 thousand times. </p>
  
  <p>The WinForms application sends a parameter to the business class and has an area to display the time taken for each method call and what the value returned by the method. How do I inform my main window and update a text area in the main winform with what the method has returned for each call?   </p>
  
  <p>Currently the data comes all at once after all the threads have finished. Is there a way to update the UI for all the iterations of the loop once the each call is done? I don't mind if it is done sequentially also.</p>
  
  <p>The FORM </p>
  
  <pre><code>    HeavyDutyClass hd;
      public Form1()
      {
          InitializeComponent();
          hd = new HeavyDutyClass();
      }
  
  
      //BUTTON CLICK
      private void Start_Click(object sender, EventArgs e)
      {
  
          int filecount = 5000;  //BAD - opening 5000 threads! Any other approach?
          hd.FileProcessed += new EventHandler(hd_FileProcessed);
  
  
          var threads = new Thread[filecount];
  
          for (int i = 0; i &lt; filecount; i++)
          {
              threads[i] = new Thread(() =&gt; { hd.LongRunningMethod(); });
              threads[i].Start();   
          }
  
      }
  
      //BUSINESS CLASS EVENT THAT FIRES WHEN BUSINESS METHOD COMPELTES
      void hd_FileProcessed(object sender, EventArgs e)
      {
  
          if (dgv.InvokeRequired)
          {
              dgv.Invoke((MethodInvoker)delegate { UpdateGrid(); });
  
          }
      }
  
      private void UpdateGrid()
      {
          dgv.Rows.Add(1);
          int i = dgv.Rows.Count;
          dgv.Rows [ i-1].Selected = true;
          dgv.FirstDisplayedScrollingRowIndex = i - 1;
  
      }
  </code></pre>
  
  <p>The business HeavyDuty class</p>
  
  <pre><code>    public event EventHandler FileProcessed;
  
      public HeavyDutyClass()
      {
      }
  
      protected virtual void OnMyEvent(EventArgs e)
      {
          if (FileProcessed != null)
          {
              FileProcessed(this, e);
          }
      }
  
      public bool LongRunningMethod()
      {
          for (double i = 0; i &lt; 199990000; i++)
          {
              //time consuming loop
          }
          OnMyEvent(EventArgs.Empty);
          return true;
      }
  </code></pre>