在处理invokeRequired之前抛出跨线程的invalidOperationexception

时间:2017-03-06 15:50:07

标签: c# multithreading textbox console.writeline

我导入json文件并通过Console.WriteLine将其内容显示到文本框中。我使用了多个线程,因为我想取消其内容的编写,并且已经读过你需要在使用多个线程时调用写入文本框但我无法使其工作。当if(output.InvokeRequired)运行时,它会抛出有关不安全的跨线程调用的错误,而且我不知道为什么。

这里是代码:

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

以及负责事件处理程序的部分:

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

1 个答案:

答案 0 :(得分:1)

您需要执行import matplotlib.pyplot as plt import gact fig, ax = plt.subplots(figsize=(10,3)) all_scores = ALL_SCORES2 x = 1 maxi = 0 for scores in all_scores: y = 0 for base, score in scores: gact.letterAt(base, x,y, score, ax) y += score x += 1 maxi = max(maxi, y) plt.xticks(range(1,x)) plt.xlim((0, x)) plt.ylim((0, maxi)) plt.tight_layout() plt.show() 而不是<?php $curl = curl_init("http://localhost/web_service/base.txt"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $answer = curl_exec($curl); $info = curl_getinfo($curl); if ($info['http_code' == 200] ){ $data = explode(",", $answer); foreach ($data as $fruit) { echo "-> ". $fruit ."<br>"; } } else { echo "error" . curl_error($curl); } ?>,因此您正在调用正确的帖子。