如何妥善处置一WebResponse的实例? [英] How to properly dispose of a WebResponse instance?
问题描述
通常,一个写code像这样使用一个WebRequest的下载一些数据。
Normally, one writes code something like this to download some data using a WebRequest.
using(WebResponse resp = request.GetResponse()) // WebRequest request...
using(Stream str = resp.GetResponseStream())
; // do something with the stream str
现在,如果引发WebException,该WebException具有参考WebResponse对象,这可能会或可能不会有所谓的Dispose(不同的地方除了已经发生,或如何响应类实现) - 我不知道知道了。
Now if a WebException is thrown, the WebException has a reference to the WebResponse object, which may or may not have Dispose called (depending on where the exception has happened, or how the response class is implemented) - I don't know.
我的问题是如何一个应该解决这个问题。是应该被编码非常防守和处置在WebException对象的反应(这将是一个有点古怪,因为WebException不是IDisposable接口)的。或者是一款应该忽略这一点,可能会访问一个释放的对象或从未处理一个IDisposable的对象呢? MSDN文档WebException.Response中给出的例子是完全不够的。
My question is how one is supposed to deal with this. Is one supposed to be coding very defensively, and dispose of the response in the WebException object (that would be a little weird, as WebException is not IDisposable). Or is one supposed to ignore this, potentially accessing a disposed object or never disposing an IDisposable object? The example given in the MSDN documentation for WebException.Response is wholly inadequate.
推荐答案
我有一个快速浏览与反射,而现在可以说:
I have had a quick peek with Reflector, and can now say:
-
WebResponse类
,是一个抽象类,委托其全部关闭/处置行为,它的派生类。 -
HttpWebResponse
,是你几乎可以肯定,这里使用的派生类,在其关闭/处置方法,是只关注配置和实际响应流。之类的状态,其余的可以留到GC的慈悲。
WebResponse
, being an abstract class, delegates all its closing/disposing behaviour to its derived classes.HttpWebResponse
, being the derived class you are almost certainly using here, in its close/dispose methods, is only concerned with disposing the actual response stream. The rest of the class state can be left to the GC's tender mercies.
由此可见,它可能是安全的,做任何你喜欢就异常处理,只要:
It follows that it's probably safe to do whatever you like with regard to exception handling, as long as:
- 当你读
WebResponse类
在尝试
块中的响应流,封装在一个使用
块。 - 的如果的你读
WebException
在抓
块中的响应流,封闭它在一个使用
块为好。 - 在没有必要担心处理
WebException
本身。
- When you read the response stream from
WebResponse
in thetry
block, enclose it in ausing
block. - If you read the response stream from
WebException
in thecatch
block, enclose it in ausing
block as well. - There is no need to worry about disposing of
WebException
itself.
这篇关于如何妥善处置一WebResponse的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!