1

I have data being read from a UDP port in another thread. I start the UDP client using a Task, and raise the event when a certain criteria is met. The event is subscribed within my button thread. But when I try to update my label, it gives an error that "lblHeartbeat" accessed from a thread other than the thread it was created on. Isn't it now within the correct thread?

within my UI, I have:

    private void btnMyButton_Click(object sender, EventArgs e)
    {

            Task.Factory.StartNew(() => SetName(obj1, obj2, obj3));

        myListiner.MessageReceived += (s) => lblHeartRate.Text = s;


    }


    public void SetName(object obj1, object obj2, object obj3)
    {

        myListiner.SpreadValue(obj1, obj2, obj3);

    }
Luke Zhang
  • 343
  • 1
  • 4
  • 14

1 Answers1

0

If the exception notifys you about cross-thread activity the only thing that helps is invoking:

synchronous: Control.Invoke()
asynchronous: Control.BeginInvoke()

If not sure whether to invoke or not you should use Control.InvokeRequired.

You can use Invoke.Required recursively. Here is a C++-code for it:

void FormMain::OnEvent(Object^  sender, EventArgs^  e){
if (this->InvokeRequired)
    this->Invoke(gcnew EventHandler(this, &FormMain::OnEvent), sender, e);
else
{
    // here is your code to run in GUI thread
}

}

Matthias
  • 37
  • 8