Making Thread-Safe Calls to labels in Windows Forms Controls

大城市里の小女人 提交于 2019-12-24 20:15:36

问题


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:

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

回答1:


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


来源:https://stackoverflow.com/questions/18114028/making-thread-safe-calls-to-labels-in-windows-forms-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!