Serial Port and ObjectDisposedException Safe Handle has been closed

↘锁芯ラ 提交于 2019-12-13 05:50:56

问题


I am receiving data from a device that's sending information over the serial port and I get this exception: "ObjectDisposedException Safe Handle has been closed". It may happen within seconds to several minutes and there doesn't seem to be a pattern. Another thing that happens is that it will stop receiving data with no exception and I can see in the VS IDE output window tab that a thread has exited. I have no idea why it's doing that also.

Here is how I create the serial port:

DeviceSerialPort serialport = new DeviceSerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
serialport.RHDataReceived += new EventHandler<DeviceDataEventArgs>(SerialPort_RHDataReceived);
serialport.Open();

And here is the serial port code:

namespace Instrument
{
    public class DeviceSerialPort
    {
        public event EventHandler<DeviceDataEventArgs> RHDataReceived;

        private SerialPort _serialPort;
        private byte[] _readBuffer = new byte[1024];

        public DeviceSerialPort(string portName, int baudRate, Parity parity, 
            int dataBits, StopBits stopBits)
        {
            _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            _serialPort.DataReceived +=new SerialDataReceivedEventHandler(SerialPort_DataReceived);

        }

        public void Open()
        {
            _serialPort.Open();
        }

        private void SerialPort_DataReceived(object sender, EventArgs e)
        {
            //SerialPort sp = (SerialPort)sender;

            int bytesRead = _serialPort.Read(_readBuffer, 0, _readBuffer.Length);


            if (_readBuffer[0] == 5)
            {
                onRHDataReceivedEvent(new DeviceDataEventArgs(_readBuffer[0], _readBuffer[1], _readBuffer[2], _readBuffer[3]));
            }
        }


        protected void onRHDataReceivedEvent(DeviceDataEventArgs e)
        {
            if (RHDataReceived != null)
            {
                RHDataReceived(this, e);
            }
        }

    }

    public class DeviceDataEventArgs : EventArgs
    {
        public byte Command { get; set; }
        public byte Data0 { get; set; }
        public byte Data1 { get; set; }
        public byte Crc { get; set; }

        public DeviceDataEventArgs(byte cmd, byte data0, byte data1, byte crc)
        {
            Command = cmd;
            Data0 = data0;
            Data1 = data1;
            Crc = crc;
        }
    }
}

回答1:


Your thread is very short lived, it lives for exactly the length of time it takes to open the serial port, and then it finishes. And when it does, your serial port gets disposed.

This is how I see it. You're using an event-based approach (handling the DataReceived event), in which case, you don't need another thread, which is expensive in terms of framework and OS resources. In your case, simply get rid of the Thread object, and call serialPort.Open() directly. You will receive the DataReceived events in your existing thread.




回答2:


Register the unhandled exception handler in form_load using:

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException_Handler

And add the handler:

'This sub does the magic
Private Sub UnhandledException_Handler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
    Dim ex As Exception = DirectCast(args.ExceptionObject, Exception)
    Thread.CurrentThread.Suspend()
End Sub


来源:https://stackoverflow.com/questions/1964104/serial-port-and-objectdisposedexception-safe-handle-has-been-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!