C#: "Using" Statements with HttpWebRequests/HttpWebResponses

Maxim Zaslavsky picture Maxim Zaslavsky · Dec 28, 2009 · Viewed 29.3k times · Source

Jon Skeet made a comment (via Twitter) on my SOApiDotNet code (a .NET library for the pre-alpha Stack Overflow API):

@maximz2005 One thing I've noticed just from browsing the source quickly: you don't disposed (sic) of WebResponses. "using" statements FTW.

He indicates that I need to wrap these Web sessions in "using" statements. However, I have a question about this: should I wrap the whole thing, starting with the HttpWebRequest, or should I create the WebRequest outside of the "using" statement and then wrap the Response inside? I have a feeling that the difference is that, in the former, both objects would be disposed of - is this correct?

Thanks in advance.

Answer

Dzmitry Huba picture Dzmitry Huba · Dec 28, 2009

HttpWebRequest itself is not disposable unlike HttpWebResponse. You should wrap disposable resources with using to allow early and determined cleanup. Correctly implemented IDisposable pattern allows multiple calls to Dispose without any issues so even the outer using statement wraps resource that during its own dispose disposes inner using statement resource it is still ok.

Code example

var request = (HttpWebRequest)WebRequest.Create("example.com"); 
using (var response = (HttpWebResponse)request.GetResponse()) 
{ 
    // Code here 
}