How to properly dispose of a WebResponse instance?

前端 未结 6 411
轻奢々
轻奢々 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.

提交回复
热议问题