I have a windows form application in C#.Where i have a RichTextBox(Txt) in the Main window(MainForm) and a public method
public void postTxt(String txt)
{
//do some database update
this.Txt.AppendText(txt);
}
I have another Form called SerialTranseiver(MainForm mn) which is passed the MainForm as a parameter in the constructor.
SerialTranseiver(MainForm mn)
{
//-----other codes
this.tmpMain=mn;
}
This second class has a SerialPort(Sport) and waits for data and whenever data found in its
SerialDataReceivedEventHandler calls mn.postTxt(Sport.ReadLine().toString())
void Sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
mn.postTxt(Sport.ReadLine().toString());
//---database updating codes and other stuff
}
this causes an exception that says
Cross-thread operation not valid: Control 'Txt' accessed from a thread other than the thread it was created on
How can i solve this problem?
One way is to invoke a delegate asyncronously which is made public in the form you invoke it on. For example:
I’d suggest you reading this first and this afterwards