简体   繁体   English

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

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

The error I'm having from my thread is: 我在线程中遇到的错误是:

Cross-thread operation not valid. 跨线程操作无效。 Control 'richTextBox8' accessed from a thread other than the thread it was created on. 控件“ richTextBox8”是从不是在其上创建线程的线程访问的。

I have this code I use for my List of string that is causing the error. 我将这段代码用于导致错误的字符串列表。

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

Now I'm working with using System.Threading that requires to transform the code above into a format something like this code to work but I'm unable to do it or is there some other way? 现在,我正在使用System.Threading,它需要将上面的代码转换为类似于此代码的格式才能正常工作,但我无法执行此操作,或者还有其他方法吗?

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

your string array (string[]) looks fine to me. 您的字符串数组(string [])在我看来还不错。 If there are whitespaces inisde richTextBox8 it should do the splitting. 如果inisde richTextBox8中存在空格,则应进行拆分。

Regarding your Threading, try with a use of delegate, like: 关于线程,请尝试使用委托,例如:

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

You only need the text extraction done on the UI thread. 您只需要在UI线程上完成文本提取即可。

With variable capturing : 使用变量捕获

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

Without variable capturing (slightly more efficient): 没有变量捕获(效率略高):

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