I have a program which monitors a TCP connection for any data and fires an event when an entire message has been recieved. The listener is on a different thread from the UI Thread. When the event is fired, if the message requires any UI changes, I invoke the Form with the current change. If this invoke is ever hit, the function in the listener that triggered off the Event flags up a Cross-Thread operation not valid error. I dont understand why the thread that called the event would flag up that error when i am trying to avoid that error by invoking. Example:
Without the Invoke on the command:
if (cmd == "NEWID")
{
usr = new User(usr.Name, int.Parse(NW_Connector.GetWord(msg, 1)));
this.Text = "Note It - " + usr.Name + "(" + usr.ID + ")"; //Cross-Thread Here
}
Cross-Thread is flagged on the this.Text change.
When i add the Invoke:
if (cmd == "NEWID")
{
usr = new User(usr.Name, int.Parse(NW_Connector.GetWord(msg, 1)));
this.Invoke(new MethodInvoker(delegate { this.Text = "Note It - " + usr.Name + "(" + usr.ID + ")"; }));
}
The Cross-Thread is flagged on the function that fired the event:
if (NewMessage != null && NetworkConnectionState != ConnectionState.Closing)
NewMessage(this, cl, data); //Cross-Thread Here
The NewMessage function is the event that is registered to:
public delegate void RecievedMessage(object sender, Client messageSender, byte[] message);
public event RecievedMessage NewMessage;
I dont understand why the Cross-thread is “moved” when invoking to the correct thread. Any help would be Fantastic!
I have absolutely no idea why, but doing a complete rebuild (rebuilding every project in the solution) Rectified the issue. The issue must then have been because the source code of the project i was changing was different from the operating programs source it was showing the Cross-Thread error at the closest possible valid source code avaliable on the stack trace.
Strange i was not alerted that the source code was different But it has however fixed the issue. I hope this will help someone else with the same issue. It really freaked me out WHY the Cross-Thread issue would appear to be “falling back” to a previous location in the stack trace.