I’m having a problem with the SerialPort class.
We’re using multiple serialports in a generic list since we need to connect to multiple devices.
This is what our basic code looks like:
List<SerialPort> ports = new List<SerialPort>(); private void button1_Click(object sender, EventArgs e) { ports.Add(new SerialPort('COM6')); ports.Add(new SerialPort('COM7')); ports.Add(new SerialPort('COM8')); foreach (SerialPort port in ports) { port.Open(); } }
Now, after the button is clicked, if one of the devices (mobile phone in our case) is switched off or if its cable is disconnected from the USB port,there is an immediate massive memory leakage.
I have noticed a similar thread here and a couple of bug reports in Microsoft Connect.
Are you sure that the problem is with
SerialPortand not the driver for the USB-Serial device? I would try another test to validate the issue:hypertermIf it does not happen, then there is a bug in particular to
SerialPort. If it happens again, you would at least know that it has nothing to do withSerialPort‘s implementation. The problem might be in either the Window’s COM Port code or in the driver you are using. Personally, I find it likelier that it the problem might be in the driver, but I’d love to know if there is some unknown issue with Window’s serial ports.I’ve used
SerialPortbefore while connecting/disconnecting ports without any such problems.Another thing you can try to is debug into the CLR’s code. There are plenty of other SO questions on this topic, so it should be easy to find the method to do that. That should let you debug down a bit further and see exactly at which point in
Open()the memory leak happens. Warning though, since it is a ‘simple’ wrapper to the system’s serial port, you might quickly see it go to P/Invoke world and will probably not get to see to much.