Cancelling BackgroundWorker While Running

Posted by Nevets on Stack Overflow See other posts from Stack Overflow or by Nevets
Published on 2014-06-03T17:52:19Z Indexed on 2014/06/04 15:25 UTC
Read the original article Hit count: 154

Filed under:
|

I have an application in which I launch a window that displays byte data coming in from a 3rd party tool. I have included .CancelAsync() and .CancellationPending into my code (see below) but I have another issue that I am running into.

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    Thread popupwindow = new Thread(() => 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());
   }
}

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.

LogWindow code for Rich Text Box:

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();
        }));
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about backgroundworker