Question

i'm writing a program for WinCE6 in C# , using Network (TCP/IP) and Serialport. i used a thread for socket listening and as data received i want to show it in a label on form. but there is an error for accessing controls in Threads and i wanted to solve it with and Invoke - BeginInvoke command but didn't work. Neither BackgroundWorker!

if (txtTCPRecieve.InvokeRequired)
{
    SetTextCallback d = new SetTextCallback(SetText);
    txtTCPRecieve.Invoke(d);
}

delegate void SetTextCallback();

void SetText()
{
    label3.Text = stringData;
}

is there any one can help?

tnx

Was it helpful?

Solution

Everytime I need to update UI elements from a background thread I use the following code (here to update a textbox named "txtLog":

    delegate void SetTextCallback(string text);
    public void addLog(string text)
    {
        // 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 (this.txtLog.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(addLog);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            txtLog.Text += text + "\r\n";
            //scroll to updated text
            txtLog.SelectionLength = 0;
            txtLog.SelectionStart = txtLog.Text.Length - 1;
            txtLog.ScrollToCaret();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top