交叉线程操作错误

Avi*_*vik 0 c# multithreading

      if (listBox1.InvokeRequired)
       {
           listBox = new StringBuilder(this.listBox1.Text);
       }
Run Code Online (Sandbox Code Playgroud)

这是c#中的代码,执行时会为listBox1生成无效的交叉线程操作错误,listBox1是我表单中的列表框.请你们告诉我为什么?我也使用invokeRequired方法,也没有更改列表框的内容.

Jar*_*Par 5

InvokeRequired仅告诉您需要Invoke才能有效地访问该元素.它不会使访问合法.您必须使用invoke方法将更新推送到适当的线程

Action update = () => listbox = new StringBuilder(this.listBox1.Text);
if (listBox1.InvokeRequired) {
  listBox1.Invoke(update);
} else {
  update();
}
Run Code Online (Sandbox Code Playgroud)