VS 2022 Debugger causing System.ObjectDisposedException: 'Safe handle has been closed.'

87 Views Asked by At

I have a single-threaded application in NET6.0 with VS2022. With the debugger, I randomly get this exception:

System.ObjectDisposedException: 'Safe handle has been closed. Object name: 'SafeHandle'.'

It happens only with my class that wraps a SerialPort. I have an equivalent class which wraps TcpClient and has no issue.

Here's an example code

class SerialDriver
{
    byte[] buf;
    SerialPort port;

    void Connect(); // port.Open() + a few writes and reads
    void Disconnect(); // port.Close()
    int Read(); // Synchronous read
}

void Main()
{
    SerialDriver s = new SerialDriver("COM5");
    s.Connect();

    // Using the debugger from here on causes SafeHandle Exception,
    // even on lines that do not referecnce the serial port at all.

    for(int i = 0; i < 10; i++)
    {
        int len = s.Read();
        Thread.Sleep(10000);
    }
    s.Disconnect();
}
  • "Step Over" or "Step Into" - About 2 or 3 clicks before exception
  • "Continue" between breakpoints - About 7 to 10 before exception
  • No Breakpoints, or no debugger - No exception.

Has anyone encountered an issue with the debugger?

0

There are 0 best solutions below