Search code examples
c#multithreadingtextboxconsole.writeline

Cross-thread invalidOperationexception is thrown before invokeRequired is handled


I'm importing a json file and display its contents through Console.WriteLine to a textbox. I used multiple threading because I would like to cancel the writing of its contents and have read about that you need to Invoke the writing to a textbox when using multiple threading but I can't get it to work. It throws the error about unsafe cross-thread calls when if(output.InvokeRequired) runs and I have no clue why.

here's the code:

public class TextBoxStreamWriter : TextWriter
{
  TextBox _output = null;

  public TextBoxStreamWriter(TextBox output)
  {
      _output = output;
  }

  public override void Write(char value)
  {
      base.Write(value);
      if (_output.InvokeRequired)
      {
          this.Invoke((MethodInvoker)(() => _output.AppendText(value.ToString())));
      }
  }

  public override Encoding Encoding
  {
      get { return System.Text.Encoding.UTF8; }
  }
}

and the part that is responsible for the event-handlers:

private void goButton_Click(object sender, EventArgs e)
{
    _worker = new BackgroundWorker();
    _worker.WorkerSupportsCancellation = true;

    _worker.DoWork += new DoWorkEventHandler((state, args) =>
    {
        do
        {
           if (_worker.CancellationPending) break;

           Console.WriteLine("Hello, world");

        } while (true);
    });

    _worker.RunWorkerAsync();
    goButton.Enabled = false;
    stopButton.Enabled = true;
}

private void stopButton_Click(object sender, EventArgs e)
{
   stopButton.Enabled = false;
   goButton.Enabled = true;
   _worker.CancelAsync();
}

Solution

  • You need to do _output.Invoke instead of this.Invoke so you are invoking on the correct thread.