I'm using the .NET System.IO.Ports.SerialPort using the BaseStream as suggested in this post If you must use .NET System.IO.Ports.SerialPort
But when I try to close the port or the baseStream, an System.InvalidOperationException is raised saying "The BaseStream is only available when the port is open"
This is my code:
private void ActionStarted() { //ajusta el puerto setupSerial(); serial.Open(); //conecta al plc byte[] buffer = new byte[15]; Action kickoffRead = null; if (serial.IsOpen) //si esta abierto el puerto hace todo esto { kickoffRead = delegate() { serial.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult ar) { try { int actualLength = serial.BaseStream.EndRead(ar); byte[] received = new byte[actualLength]; Buffer.BlockCopy(buffer, 0, received, 0, actualLength); raiseAppSerialDataEvent(received); } catch { } kickoffRead(); }, null); }; kickoffRead(); } }
and the error occurrs when I try to close the window / port / basestream here,
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { serial.BaseStream.Flush(); serial.BaseStream.Close(); serial.Close(); }
I read somewhere that the serial port should be close on a different thread but I can't find that, so any thoughts??
Thanks!!