How to properly dispose of a WebResponse instance?

前端 未结 6 364
轻奢々
轻奢々 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:29
    using (var x = GetObject()) {
         statements;
    }
    

    is (almost) equivalent to

    var x = GetObject();
    try {
        statements;
    }
    finally {
         ((IDisposable)x).Dispose();
    }
    

    so your object will always be disposed.

    This means that in your case

    try {
        using (WebResponse resp = request.GetResponse()) {
            something;
        }
    }
    catch (WebException ex) {
        DoSomething(ex.Response);
    }
    

    ex.Response will be the same object as your local resp object, which is disposed when you get to the catch handler. This means that DoSomething is using a disposed object, and will likely fail with an ObjectDisposedException.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 23:34

    A very interesting question (although worth pointing out that the WebResponse object will have been disposed as you exit the using). My gut feeling is that it doesn't really matter that you've got a reference to this disposed WebResponse object as long as you don't try to do anything "operational" with it.

    You can probably still access certain properties on the instance for logging purposes (such as the ResponseUri) without getting an ObjectDisposedException, but overall reference held by the exception is not there so you can continue using the instance.

    I'd be interested to see what others say.

    0 讨论(0)
  • 2021-01-03 23:39

    I get similar cases in EF DB connections.

    So i actually create a connections list.

    At the end of game , i loop dispose all of them.

    0 讨论(0)
  • 2021-01-03 23:47

    I'm pretty sure that when you have a using statement the object is disposed, regardless of how you exit the using block (Be it via exception, return or simply progressing through the function).

    I suspect you'll find that the object inside the WebException has already been disposed if you let it leave the using block.

    Remember, disposing of an object doesn't necessarily prevent accessing it later. It can be unpredictable to try to call methods on it later, causing exceptions of it's own or very weird behavior (And hence I wouldn't recommend it). But even still a large portion of the object is still left behind for the garbage collector even if you dispose it, and hence is still accessible. The purpose of the dispose is typically to clean up resource handles (Like in this case active TCP connections) that for performance reasons you can't realistically leave laying around until the garbage collector finds them. I only mention this to clarify that it's not mutually exclusive for it to be disposed and the exception to hold a reference to it.

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题