多线程中的toolStripStatusLabel

时间:2013-04-24 00:15:04

标签: c# multithreading winforms

我在多线程中使用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);

1 个答案:

答案 0 :(得分:1)

这是因为拥有线程是您从[{1}}调用的任何主题 - 您正在使用safeThreaded()StatusStrip创建表单,然后在同一个帖子中编辑它。

如果你要在一个线程中创建Form,然后在一个单独的线程中运行你的ToolStripStatusLabel函数(不带在其中创建safeThreaded()),那么你应该看到Form2是真的。

相关问题