I have a C# DLL written to connect a VB6 (yes, I know - legacy code) industrial application to a third-party web service. My code works the way I want it to now, but I had hit a bit of a snag the other day.
The application works the way I want on the first usage, but hangs on subsequent iterations leading up to an application time-out. After some debugging I found that my method I've used to check for a connection to the web service does not release its objects automatically.
private bool connected()
{
string url = "http://location-Im-connecting-to";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
try
{
// String element to capture response from service
whatHappened = response.StatusCode.ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
// it's at least in some way responsive
isConnected = true;
}
else
{
// well, at least it returned...
isConnected = false;
}
}
catch (Exception ex)
{
// not available at all, for some reason
isConnected = false;
whatHappened = response.StatusCode.ToString();
}
// My solution to closing out the hanging method
response.Close();
response.Dispose();
request.Abort();
return isConnected;
}
Implementing the three lines to close out the method's objects now allows my DLL to work the way I want for every iteration. So my question is this: even though my brute-force approach has worked for releasing the method's objects it does not have a finessed way of automatically shutting down the method's objects. Does our SO community have any suggestions for cleaning up my solution, or is the above the best I can hope for? Is there a way to wrap up the HTTPWebResponse
in a using()
statement as was suggested in the comments for HttpWebResponse: closing the stream?
Note: I am aware that the response.Dispose()
may be redundant, but I am asking for advice on the format for improving the flow of the code.