clonesegg
clonesegg

Reputation: 245

returning iDisposable from method - whos is responsible for disposing?

Given the following code:

    using (var webResponse = GenerateWebrequest(postURL, postParameters))
        {
            using (var stream = webResponse.GetResponse())
            {
                if (stream != null)
                {
                    xmlDoc.Load(stream);
                }
            }

            webResponse.Close();
        }

which calls the method:

private HttpWebResponse GetResponse(string postUrl, byte[] formData)
    {
       var request = WebRequest.Create(postUrl) as HttpWebRequest;
       //other code to set up request here...

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(formData, 0, formData.Length);
            requestStream.Close();
        }

        return request.GetResponse() as HttpWebResponse;
    }

My question is basically this:

The calling code wraps the method call in a using and disposes of the response stream.

But what should happen if request.GetResponse() in the GenerateWebrequest fails? Should I simply wrap it in a try catch? What do i return then?

Upvotes: 3

Views: 327

Answers (1)

Anders Abel
Anders Abel

Reputation: 69260

There's a special pattern to use for methods returning IDisposable objects:

HttpWebRequest tmpRequest;
try
{
  tmpRequest = WebRequest.Create(postUrl) as HttpWebReqeust;

  // Whatever other stuff...

  // When all other work is done. No code that can cause an exception
  // should exist below this line.
  var returnRequest = tmpReqeust;
  tmpRequest = null;

  return returnRequest;
}
finally
{
  if(tmpRequest != null)
    tmpRequest.Dispose();
}

The pattern also works for constructors creating nested IDisposable objects and for methods creating multiple IDisposable objects.

Upvotes: 2

Related Questions