c# - "Cross thread operation not valid" .. while reading data on Serial Port -


In a window form, on main form load, I have set a serial port and have started reading it. Objective After receiving some data on the serial port, I want to open any other form related to the data.

That's why I use the Datawar event handler of the serial port.

  Zero serial PORT1_DataReceived (Object Sender, System.IO.Ports.SerialDataReceivedEventArgs E) {string str = this.serialPort1.ReadLine (); If (! String.isnaloractic (ARR)) {main sequence. Customer Data = New Customer Data (ARR); Main. Instance CustomerData.mdpear = main Instance; // The head was received at this point. Instance customer data. Dispared + = new event heredollar (customerData_Disposed); Main.Instance.customerData.Show (); }}   

But when I try to open a form inside an event handler, I'm saying a normal operation reception: "Cross-thread operation is not valid: Control 'Main' The thread was moved from one place to the other. "

I tried to remove the code line: main. Instance CustomerData.mdpear = main Instance; Then it works fine.

Any suggestions to solve this problem?

Use the ion method primarily. To interact with it you have to control the main form. Event handler is triggered on the background thread.

Here is some sample code that can work:

  Zero serial port 1_DataReceived (Object Sender, System.IO.Ports.SerialDataReceivedEventArgs e) {String str = this .serialPort1.ReadLine (); If (! String. ISNLLlight (ARR)) {ShowCustomerData (str); }} Personal Representative Zero ShowCustomerDataDelegate (String S); Private Zero ShowCustomerData (strings) {if (Main.Instance.InvokeRequired) {Main.Instance.Invoke (New ShowCustomerDataDelegate (ShowCustomerData), S); } And {main. Instance Customer Data = New Customer Data (str); Main. Instance CustomerData.mdpear = main Instance; // The head was received at this point. Instance customer data. Dispared + = new event heredollar (customerData_Disposed); Main.Instance.customerData.Show (); }}    

Comments