对Windows窗体控件中的标签进行线程安全调用

时间:2013-08-07 21:20:39

标签: multithreading winforms delegates c++-cli

我正在Microsoft Visual Studio中的Visual C ++中创建一个小应用程序,我在一个线程中收集数据并在Windows窗体中的标签中显示信息。我正在尝试按照本文/教程关于如何调用标签线程安全:http://msdn.microsoft.com/en-us/library/ms171728(VS.90).aspx。该示例显示如何将文本输出到一个文本框,但我想输出到许多标签。当我尝试时,我得到错误:

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

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

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

1 个答案:

答案 0 :(得分:0)

除了Label之外,您还需要修改委托以获取string

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

然后用两个参数调用它:

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;
    }
}
相关问题