How to properly dispose of a WebResponse instance?

前端 未结 6 398
轻奢々
轻奢々 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:31

    HttpWebRequest internally makes a memory stream off the underlying network stream before throwing WebException, so there is no unmanaged resource associated with the WebResponse returned from WebException.Response.

    This makes it unnecessary to call Dispose() on it. In fact, trying to dispose WebException.Response can cause headache and issues because you may have callers of your code that is attempting to read properties associated with it.

    However it is a good practice that you should dispose any IDisposable objects you own. If you decide to do so, make sure you don't have code depending on being able to read WebException.Response properties and/or its stream. The best way would be you handle the exception and throw new type of exception so that you don't leak WebException up to the caller when possible.

    And also consider moving to HttpClient which replaces HttpWebRequest.

    Disclaimer: No warranty implied.

提交回复
热议问题