Search code examples
c#timeoutusinghttpwebresponseout

How to use 'using' with 'out' parameter


I have a method like so

private bool VerbMethod(string httpVerb, string methodName, string url, string command, string guid, out HttpWebResponse response)

I use this like this

  HttpWebResponse response;
  if (VerbMethod("POST", "TheMethod", "http://theurl.com", "parameter1=a", theGuid, out response))
  {
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
      string responseString = sr.ReadToEnd();
    }

It returns a bool to specify if the method went well, and the response is set in an out parameter to get the data.

I sometimes get a timeout, and then subsequent requests also times out. I saw this SO WebRequest.GetResponse locks up?

It recommonds the using keyword. The problem is, with the above method signature I'm not sure how to do it.

  • Should I manually call dispose in a finally?
  • Is there some way to still use using with the out parameter?
  • Rewrite the method, so it doesn't expose the HttpWebResponse?

Solution

  • It returns a bool to specify if the method went well

    That's your problem. Don't use a Boolean success value: throw an exception if something goes wrong. (Or rather, let the exception bubble up.)

    Just change your method to return the response.