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

时间:2015-02-13 10:56:57

标签: c# .net idisposable

给出以下代码:

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

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

调用代码将方法调用包装在一个使用中,并处理响应流。

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

1 个答案:

答案 0 :(得分:2)

有一种特殊模式可用于返回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对象的方法。