对Windows窗体控件中的标签进行线程安全调用 [英] Making Thread-Safe Calls to labels in Windows Forms Controls

查看:90
本文介绍了对Windows窗体控件中的标签进行线程安全调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Microsoft Visual Studio的Visual C ++中制作一个小型应用程序,在其中我正在线程中收集数据并在Windows窗体的标签中显示信息.我正在尝试遵循有关如何使对标签线程的调用安全的这篇文章/教程:

I am making a small app in Visual C++ in Microsoft Visual Studio where I am collecting data in a thread and displaying the information in labels in a Windows Form. I am trying to follow this Article/Tutorial on how to make the calls to the labels thread safe: http://msdn.microsoft.com/en-us/library/ms171728(VS.90).aspx. The example shows how to output text to one text box, but I want to output to many labels. When I try I get the error:

错误C3352:'无效的APP :: Form1 :: SetText(System :: String ^,System :: Windows :: Forms :: Label ^)':指定的函数与委托类型'void(System: :String ^)'

error C3352: 'void APP::Form1::SetText(System::String ^,System::Windows::Forms::Label ^)' : the specified function does not match the delegate type 'void (System::String ^)'

以下是我正在使用的一些代码:

Here is some of the code I am using:

private:
void ThreadProc()
{
    while(!exit)
    {
        uInt8        data[100];

        //code to get data

        SetText(data[0].ToString(), label1);
        SetText(data[1].ToString(), label2);
        SetText(data[2].ToString(), label3);
        SetText(data[3].ToString(), label4);
        SetText(data[4].ToString(), label5);
        SetText(data[5].ToString(), label6);
        ...
    }
}

delegate void SetTextDelegate(String^ text);

private:
void SetText(String^ text, Label^ label)
{
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (label->InvokeRequired)
    {
        SetTextDelegate^ d =
        gcnew SetTextDelegate(this, &Form1::SetText);
        this->Invoke(d, gcnew array<Object^> { text });
    }
    else
    {
        label->Text = text;
    }
}

推荐答案

除了string之外,您还需要修改委托以采用Label:

You need to modify the delegate to take a Label in addition to the string:

delegate void SetTextDelegate(String^ text, Label^ label);

然后使用两个参数调用它:

And then call it with two parameters:

void SetText(String^ text, Label^ label)
{
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (label->InvokeRequired)
    {
        SetTextDelegate^ d =
        gcnew SetTextDelegate(this, &Form1::SetText);
        this->Invoke(d, gcnew array<Object^> { text, label });
    }
    else
    {
        label->;Text = text;
    }
}

这篇关于对Windows窗体控件中的标签进行线程安全调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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