locked
How safe is "using" RRS feed

  • Question

  • I've read the documention on using, but it is not 100% clear to me.

    Consider the following:

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(fileLocation);
    using
    (WebResponse webResponse = webRequest.GetResponse())
    {
       if (throwException)
       {
          throw new Exception();
       }
    }


    Will webResponse.Close() be automatically called on exit from the using scope?
    If throwException is true, then will webResponse.Close() still be called, or do I need a try...finally exception handler?
    I'm using WebResponse as an example here; do other .Net classes generally follow the same pattern?

    Thanks.

    Wednesday, November 16, 2005 9:07 AM

Answers

  • Yes in this situation WebResponse.Close() will always be called. The using statement is equivalent to the following code:


    WebResponse webResponse = webRequest.GetResponse();

    try
    {
       if (throwException)
       {
          throw new Exception();
       }
    }
    finally
    {
       ((IDisposable)webResponse).Dispose();
    }

     


    In this situation (and for other classes such as SqlConnection, Stream, etc) Dispose is just a synonym for Close(). So you do not need to place a try...finally block around the using statement.

    All disposable objects (ie those that implement IDisposable) work in exactly the same way.

    Wednesday, November 16, 2005 9:47 AM

All replies

  • Yes in this situation WebResponse.Close() will always be called. The using statement is equivalent to the following code:


    WebResponse webResponse = webRequest.GetResponse();

    try
    {
       if (throwException)
       {
          throw new Exception();
       }
    }
    finally
    {
       ((IDisposable)webResponse).Dispose();
    }

     


    In this situation (and for other classes such as SqlConnection, Stream, etc) Dispose is just a synonym for Close(). So you do not need to place a try...finally block around the using statement.

    All disposable objects (ie those that implement IDisposable) work in exactly the same way.

    Wednesday, November 16, 2005 9:47 AM
  • Thanks for the confirmation. That makes "using" really useful!
    Wednesday, November 16, 2005 1:35 PM