title: Cancelling BackgroundWorker While Running
body: <p>I have an application in which I launch a window that displays byte data coming in from a 3rd party tool. I have included <code>.CancelAsync()</code> and <code>.CancellationPending</code> into my code (see below) but I have another issue that I am running into.</p>
  
  <pre><code>private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  {
      Thread popupwindow = new Thread(() =&gt; test());
      popupwindow.Start(); // start test script
  
      if(backgroundWorker.CancellationPending == true)
      {
         e.Cancel = true;
      }
  }
  
  private voide window_FormClosing(object sender, FormClosingEventArgs e)
  {
     try
     {
        this.backgroundWorker.CancelAsync();
     }
     catch (Exception ex)
     {
        MessageBox.Show(ex.Message.ToString());
     }
  }
  </code></pre>
  
  <p>Upon cancelling the test I get an `InvalidOperationException occurred" error from my rich text box in my pop-up window. It states that "Invoke or BeginInvoke" cannot be called on a control until the window handle has been created". I am not entirely sure what that means and would appreciate your help.</p>
  
  <p>LogWindow code for Rich Text Box:</p>
  
  <pre><code>public void LogWindowText(LogMsgType msgtype, string msgIn)
      {
          rtbSerialNumberValue.Invoke(new EventHandler(delegate
          {
              rtbWindow.SelectedText = string.Empty;
              rtbWindow.SelectionFont = new Font(rtbWindow.SelectionFont, FontStyle.Bold);
              rtbWindow.SelectionColor = LogMsgTypeColor[(int)msgtype];
              rtbWindow.AppendText(msgIn);
              rtbWindow.ScrollToCaret();
          }));
      }
  </code></pre>