Close your web connections too!
In an earlier post, I had talked about a Windows service I was working on. This service periodically performs an HTTP GET request to check if a device that accepts incoming HTTP requests is still working. It was pretty simple to perform the GET with .NET -- something I'm sure many of you have done hundreds of times before.
Everything worked fine, except that after a while, I couldn't connect to the remote device and was getting a timeout. The other developer working on the device insisted that the device was running. In fact, it was still sending me data from time to time. We had a problem earlier with timeouts because a breakpoint was hit on the other device while my service was trying to send a GET request. I was sure this was the problem again.
I stopped my service and added a few more debug statements to log to the event log. When I restarted the service, everything worked fine -- for a while. Then the timeouts started again. I decided to double-check the documentation for the HttpWebResponse. Man, was I embarassed:
You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse.
Doh! I wasn't calling the GetResponseStream method since I was just interested in the Status code (I was looking for a 200 - OK). I didn't even think about the connection I was leaving open.
I wrapped the code in a try/finally that calls the Close method and things have been running smoothly ever since! ;)