C# read only Serial port when data comes -
i want read serial port when data comes(i want not polling).
this how it.
schnittstelle = new serialport("com3"); schnittstelle.baudrate = 115200; schnittstelle.databits = 8; schnittstelle.stopbits = stopbits.two; ....
and start thread
beginn = new thread(readcom); beginn.start();
and in readcom i'm reading continuous (polling :( )
private void readcom() { try { while (schnittstelle.isopen) { dispatcher.begininvoke(new action(() => { comwindow.txtbcom.text = comwindow.txtbcom.text + environment.newline + schnittstelle.readexisting(); comwindow.txtbcom.scrolltoend(); })); beginn.join(10); } } catch (threadabortexception) { } catch (exception ex) { system.windows.forms.messagebox.show(ex.tostring(), "error", messageboxbuttons.ok, messageboxicon.error); } }
i want yout read when interrupt coming. how can ?
you have add eventhandler datareceived event.
below example msdn.microsoft.com, edits: see comments!:
public static void main() { serialport myserialport = new serialport("com1"); myserialport.baudrate = 9600; myserialport.parity = parity.none; myserialport.stopbits = stopbits.one; myserialport.databits = 8; myserialport.handshake = handshake.none; myserialport.datareceived += new serialdatareceivedeventhandler(datareceivedhandler); myserialport.open(); console.writeline("press key continue..."); console.writeline(); console.readkey(); myserialport.close(); } private static void datareceivedhandler(object sender, serialdatareceivedeventargs e) { serialport sp = (serialport)sender; string indata = sp.readexisting(); debug.print("data received:"); debug.print(indata); }
everytime data comes in, datareceivedhandler trigger , prints data console. think should able in code.