title: how can i stop a thread on a usercontrol when the form is closed
body: <p>I have a user control with the following code in it:</p>
  
  <pre><code>private Thread updateProgress;
  private void FileUploadingScreen_Load(object sender, EventArgs e)
  {
      updateProgress = new Thread(UpdateProgressBar);
      updateProgress.Start();
  }
  private bool run = true;
  private void UpdateProgressBar()
  {
      while (run)
      {
          Thread.Sleep(100);
          if(run)
          {
             progressBar1.Invoke(new Action(() =&gt;
             {
                 if (progressBar1.Value &gt;= 100)
                 {
                      progressBar1.Value = 1;
                      progressBar1.Step = 1;
                 }
                 progressBar1.PerformStep();
             }));
          }
      }
  }
  
  public void StopProgressBar()
  {
      run = false;
  }
  </code></pre>
  
  <p>on the parent form I have :</p>
  
  <pre><code>private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
      userControl.StopProgressBar();
  }
  </code></pre>
  
  <p>when I close the form by clicking the X I'm getting the following error on the <code>progressBar1.Invoke</code> line.</p>
  
  <blockquote>
    <p><code>Invoke or BeginInvoke cannot be called on a control until the window handle has been created.</code></p>
  </blockquote>
  
  <p>I thought setting run to false in the <code>form_closing</code> event would stop this from happening. How can I fix this?  My main goal is to have a progressbar that keeps moving to show that something is happening still. Is there a better way to do this?</p>