【问题标题】:Cross-thread operation not valid: Control 'statusStrip' accessed from a thread other than the thread it was created on跨线程操作无效:控件“statusStrip”从创建它的线程以外的线程访问
【发布时间】:2015-05-14 12:49:03
【问题描述】:

我试过这个。 https://stackoverflow.com/a/142069/2126472

点赞toolStripStatusLabel1.InvokeRequired

但是toolStripStatusLabel1 没有InvokeRequired

我也试过这个。 https://stackoverflow.com/a/15831292/2126472

它的错误就像无效的参数一样

SetTextCallback d = new SetTextCallback(SetText); form.Invoke(d, new object[] { form, ctrl, text });

当我使用 ThreadHelperClass.SetText(this, toolStripStatusLabel1, "This text was set safely.");

但当我使用textBox时不会出错

我的代码有方法等待bool 来自另一个使用线程在后台运行的方法。

Thread t = new Thread(TestRemoteDB);
t.Start();
// In TestRemoteDB() will call updateRemoteDBStatus()

喜欢这个

private void updateRemoteDBStatus(bool successful)
        {
            if (successful)
            {
                toolStripStatusLabel4.Text = "OK!";
                toolStripStatusLabel4.ForeColor = Color.Green;
            }
            else
            {
                toolStripStatusLabel4.Text = "Error!";
                toolStripStatusLabel4.ForeColor = Color.Red;
            }
        }

【问题讨论】:

标签: c# multithreading winforms


【解决方案1】:

试试这个:

this.BeginInvoke((Action)(() => toolStripStatusLabel1.Text = "This text was set safely."));

【讨论】:

  • 这行不通,因为 ToolStripStatusLabel 没有 BeginInvoke 方法。即使这样做也没有任何意义,因为 ThreadHelperClass 已经在使用 Invoke 在 UI 线程上执行代码。而且它不会编译,因为 ToolStripStatusLabel 不是控件,因此不能与 OP 链接的 ThreadHelperClass 一起使用。
  • Lapsus,我的意思是“this”并写了“toolStripStatusLabel”。 Tnx。
  • 我认为这是可行的,并且为我节省了很多代码行。非常感谢@Marko Juvančič。
猜你喜欢
  • 2011-01-15
  • 2016-05-21
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多