从方法返回 iDisposable - 谁负责处理?

returning iDisposable from method - whos is responsible for disposing?

给定以下代码:

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

            webResponse.Close();
        }

调用方法:

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;
    }

我的问题基本上是这样的:

调用代码将方法调用包装在 using 中并处理响应流。

但是如果 GenerateWebrequest 中的 request.GetResponse() 失败会发生什么? 我应该简单地将它包装在 try catch 中吗?那我 return 怎么办?

有一种特殊模式可用于返回 IDisposable 个对象的方法:

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();
}

该模式也适用于创建嵌套 IDisposable 对象的构造函数和创建多个 IDisposable 对象的方法。