多线程中的 toolStripStatusLabel [英] toolStripStatusLabel in multithreading

查看:88
本文介绍了多线程中的 toolStripStatusLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using toolStripStatusLabel in multithreading and although it is another thread which interact with the toolStripStatusLabel my invokeRequired method of the statusStrip always return false (I enforce the creation of the handle also). In this thread I can access the toolStripStatusLabel (from else clause), update it but my editing could not be shown in the main UI. Here is my code:

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);

推荐答案

这是因为拥有线程是您从中调用 safeThreaded() 的任何线程 - 您正在使用 StatusStripToolStripStatusLabel,然后在同一个线程中编辑它们.

It's because the owning thread is whatever thread you're calling safeThreaded() from - you're creating the Form with the StatusStrip and ToolStripStatusLabel, and then editing it all in the same thread.

如果您要在一个线程中创建表单,然后运行您的 safeThreaded() 函数(在其中创建 Form2) 在一个单独的线程中,那么您应该看到 InvokeRequired 为真.

If you were to create the Form in one thread, and then run your safeThreaded() function (without creating the Form2 in it) in a separate thread, then you should see InvokeRequired be true.

这篇关于多线程中的 toolStripStatusLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆