Making Thread-Safe Calls to labels in Windows Form

2019-09-06 13:49发布

问题:

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