4
votes

Hi all i have a thread that is able to read data being received across from bluetooth stream. On the sender part i made it a while loop where count keeps on increasing + 1. I did a messagebox.show(test); and it works fine but when i do a label.text = test i get :

"Control.Invoke must be used to interact with controls created on a separate thread." error. My follow code in C# :

Thread t = new Thread(new ThreadStart(readStream)); t.Start(); public void readStream() { while (true) { String test = manager.Reader.ReadLine(); label1.Text = test; } }

My question is , how do i update the label in a thread? Any simple ways with control invoke?

1

1 Answers

6
votes

Hello here is an example how to do this:

http://msdn.microsoft.com/en-us/library/ms171728.aspx

You should use a function similar to this one if you want to update a label from another thread. You cannot update it directly.

In short: you should write something like this:

delegate void SetTextCallback(string text);

private void SetText(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.textBox1.InvokeRequired)
  { 
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
  }
  else
  {
    this.textBox1.Text = text;
  }
}