【问题标题】:toolStripStatusLabel in multithreading多线程中的 toolStripStatusLabel
【发布时间】:2013-04-17 08:55:21
【问题描述】:

我在多线程中使用toolStripStatusLabel,虽然它是另一个与toolStripStatusLabel 交互的线程,但statusStrip 的invokeRequired 方法总是返回false(我也强制创建句柄)。在这个线程中,我可以访问toolStripStatusLabel(来自 else 子句),对其进行更新,但我的编辑无法在主 UI 中显示。这是我的代码:

public void safeThreaded()
{                
    Form2 form = new Form2();
    StatusStrip ss = (StatusStrip)form.Controls["statusStrip1"];
    ToolStripStatusLabel label =   (ToolStripStatusLabel)ss.Items["toolStripStatusLabel1"];
    string text = "Written by the background thread.";
    if (!(ss.IsHandleCreated))
    {
        IntPtr handler = ss.Handle;
    }
    if (ss.InvokeRequired)
    {
        ss.Invoke(new updateTextCallback(updateText), new object[]{"Text generated on non-UI thread."});
    }
    else
    {
        // It's on the same thread, no need for Invoke
        label.Text = text + " (No Invoke)";
        MessageBox.Show(label.Text.ToString());
        ss.Refresh();
    }
}

private void updateText(string text)
{
    Form2 form = new Form2();
    StatusStrip ss = (StatusStrip)form.Controls["statusStrip1"];
    ToolStripStatusLabel label = (ToolStripStatusLabel)ss.Items["toolStripStatusLabel1"];
    label.Text = text;
}

public delegate void updateTextCallback(string text);

【问题讨论】:

    标签: c# multithreading winforms


    【解决方案1】:

    这是因为拥有线程是您从其中调用 safeThreaded() 的任何线程 - 您正在使用 StatusStripToolStripStatusLabel 创建表单,然后在同一个线程中对其进行编辑。

    如果您要在一个线程中创建表单,然后在单独的线程中运行 safeThreaded() 函数(没有在其中创建 Form2),那么您应该会看到 @987654326 @ 是真的。

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 2012-10-28
      • 2012-09-07
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多