C#从其他线程访问元素

C#从其他线程访问元素,c#,multithreading,C#,Multithreading,如何从另一个线程访问元素?在本例中,我在主线程(GUI)中有一个richtextbox,并且我正在辅助线程上运行一个方法。我想通过辅助线程访问richeditbox private void Log(string input, Label lbl) { lbl.Invoke(new Action(()=> { lbl.Text = "Status: " + input; Thread.Sleep(50); })); } void Run() {

如何从另一个线程访问元素?在本例中,我在主线程(GUI)中有一个richtextbox,并且我正在辅助线程上运行一个方法。我想通过辅助线程访问richeditbox

private void Log(string input, Label lbl)
{
  lbl.Invoke(new Action(()=>
    {
      lbl.Text = "Status: " + input;
      Thread.Sleep(50);
    }));
}

void Run()
{
   foreach (string line in richTextBox1.Lines)
    {
      Log(line, label1);
      Thread.Sleep(500);
    }
}

private void button1_Click(object sender, EventArgs e)
{
  ThreadStart th = new ThreadStart(() => Run());
  Thread th2 = new Thread(th);
  th2.Start();
  //th2.Join();
}
显示以下错误:

线程操作无效:控件“richTextBox1”是从 不是在其中创建它的线程


你已经这么做了。您的
Log
方法显示了正确的操作——使用
Invoke
在UI线程上运行一些代码。在这种情况下,您可以执行以下操作:

void Run()
{
    var getLines = new Func<object>(() => richTextBox1.Lines);
    var lines = (string[]) richTextBox1.Invoke(getLines);
    foreach (var line in lines)
    {
        Log(line, label1);
        Thread.Sleep(500);
    }
}

这是另一个版本…并不是说你不应该在Log()方法中睡觉,因为它正在UI线程中运行

private void button1_Click(object sender, EventArgs e)
{
    ThreadStart th = new ThreadStart(() => Run());
    Thread th2 = new Thread(th);
    th2.Start();
}

void Run()
{
    string[] lines = (string[])richTextBox1.Invoke(new Func<string[]>(() => richTextBox1.Lines));
    foreach (string line in lines)
    {
        Log(line, label1);
        Thread.Sleep(500);
    }
}

private void Log(string input, Label lbl)
{
    lbl.Invoke(new Action(() =>
    {
        lbl.Text = "Status: " + input;
    }));
}
private void按钮1\u单击(对象发送者,事件参数e)
{
ThreadStart th=新的ThreadStart(()=>Run());
螺纹th2=新螺纹(th);
th2.Start();
}
无效运行()
{
字符串[]行=(字符串[])richTextBox1.Invoke(新函数(()=>richTextBox1.lines));
foreach(行中的字符串行)
{
日志(行,标签1);
睡眠(500);
}
}
专用作废日志(字符串输入,标签lbl)
{
lbl.Invoke(新操作(()=>
{
lbl.Text=“状态:”+输入;
}));
}
看看这里:这里有很多(我想是44个)答案。就我个人而言,我喜欢基于水龙头的。
private void button1_Click(object sender, EventArgs e)
{
    ThreadStart th = new ThreadStart(() => Run());
    Thread th2 = new Thread(th);
    th2.Start();
}

void Run()
{
    string[] lines = (string[])richTextBox1.Invoke(new Func<string[]>(() => richTextBox1.Lines));
    foreach (string line in lines)
    {
        Log(line, label1);
        Thread.Sleep(500);
    }
}

private void Log(string input, Label lbl)
{
    lbl.Invoke(new Action(() =>
    {
        lbl.Text = "Status: " + input;
    }));
}