Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

.NET Error Closing serial port BaseStream error is only available when the port is open

$
0
0

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!!



Viewing all articles
Browse latest Browse all 8156

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>