How to properly dispose of a WebResponse instance?

前端 未结 6 366
轻奢々
轻奢々 2021-01-03 23:21

Normally, one writes code something like this to download some data using a WebRequest.

using(WebResponse resp = request.GetResponse())  // WebRequest reques         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 23:51

    I have had a quick peek with Reflector, and can now say:

    • 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:

    • When you read the response stream from WebResponse in the try block, enclose it in a using block.
    • If you read the response stream from WebException in the catch block, enclose it in a using block as well.
    • There is no need to worry about disposing of WebException itself.

提交回复
热议问题