繁体   English   中英

系统线程:跨线程操作无效

[英]System Threading: Cross-thread operation not valid

我在线程中遇到的错误是:

跨线程操作无效。 控件“ richTextBox8”是从不是在其上创建线程的线程访问的。

我将这段代码用于导致错误的字符串列表。

string[] parts = richTextBox8.Text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

现在,我正在使用System.Threading,它需要将上面的代码转换为类似于此代码的格式才能正常工作,但我无法执行此操作,或者还有其他方法吗?

richTextBox8.Invoke((Action)(() => richTextBox8.Text += "http://elibrary.judiciary.gov.ph/" + str + "\n"));

您的字符串数组(string [])在我看来还不错。 如果inisde richTextBox8中存在空格,则应进行拆分。

关于线程,请尝试使用委托,例如:

    public delegate void MyDelegate(string message);

   //when you have to use Invoke method, call this one:
   private void UpdatingRTB(string str)
   {
       if(richTextBox8.InvokeRequired)
           richTextBox8.Invoke(new MyDelegate(UpdatingRTB), new object []{ msg });
       else
           richTextBox8.AppendText(msg);
   }
string[] parts = null;
richTextBox8.Invoke((Action)(() => 
    {
        parts = richTextBox8.Text.Split(new string[] { " " },
        StringSplitOptions.RemoveEmptyEntries); //added semicolon
    }));

您只需要在UI线程上完成文本提取即可。

使用变量捕获

string text = null;
richTextBox8.Invoke((Action)(() => text = richTextBox8.Text));
string[] parts = text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

没有变量捕获(效率略高):

var ret = (string)richTextBox8.Invoke((Func<string>)(() => richTextBox8.Text));
parts = ret.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM