.NET错误关闭串行端口BaseStream错误仅在端口打开时可用 [英] .NET Error Closing serial port BaseStream error is only available when the port is open

查看:190
本文介绍了.NET错误关闭串行端口BaseStream错误仅在端口打开时可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm using the .NET System.IO.Ports.SerialPort using the BaseStream as suggested in this post <a href="http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport">If you must use NET SerialPort</a>


But when I try to close the port or the baseStream, an System.InvalidOperationException is raised saying &quot;The BaseStream is only available when the port is open&quot;

This is my code:

  <pre lang="c#">  
        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();
            }
            
        }

< br $>




当我尝试关闭窗口时,发生错误的地方,请检查:






When I try to close the window, is where the error occurs, check this:

//<-- here is where the error occurs -->
 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!!

推荐答案

I我认为tou应该只关闭串口但不关闭基本流,因为它无论如何都会关闭。该错误可能是由于串口假定流未直接关闭。



因此,您应该考虑该流由串口管理仅在端口上打开或关闭。
I would think that tou should only close the serial port but not the base stream as it will get close anyway. The error is probably caused by the fact that serial port assumes that the stream is not closed directly.

Thus you should consider that the stream is managed by the serial port and call open or close only on the port.


这篇关于.NET错误关闭串行端口BaseStream错误仅在端口打开时可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆