Wednesday 21 May 2008

System.IO.Ports.SerialPort.Close() Hangs

In the dotNET / .net framework v2 on Windows Vista, I have noticed that every so often a call to SerialPort.Close(); will hang forever (i.e. it has gone into deadlock). I read few posts of people who thought they had solved the problem with the prepending of the line SerialPort.ReadTimeout = 0;. However, I tried doing this, and although it made the occurence of the hang a lot less frequent, it still happened.

So, I thought there was no way to get around the hang, so I decided that I would close the port on a new thread, as well as having the SerialPort object contained in another object, which I would force the death of if I detected a hang. Well, funnily enough, after I did this, it would no longer hang at all. So it appeared that the problem was solved by simply creating a new thread from which to close the serial port. Strange.

In essence, by trying to find a way to handle the problem, the problem ended up going away. I'm not going to bother to find out why, I'll just be happy with that.