11

Related question: WebClient in .Net not releasing socket resources

While debugging a resource leak issue, I noticed that System.Net.WebException (a non-disposable type) contains a reference to System.Net.WebResponse (a disposable type). I am wondering if I should dispose of this reference when explicitly handling a WebResponse as in the following snippet.

using (WebClient client = new WebClient())
{
    WebException ex = Assert.Throws<WebException>(() => client.OpenRead(myUri));
    Assert.That(
        ((HttpWebResponse)ex.Response).StatusCode,
        Is.EqualTo(HttpStatusCode.ServiceUnavailable));
}

The WebException.WebResponse reference is a copy of an existing reference in WebClient. I thought that it would be disposed through WebClient.Dispose but this is not the case as WebClient does not override the protected Component.Dispose(bool) base method. In fact, disassembly suggests that the WebResponse resource is never disposed of, but rather set to null when no longer needed.

public Stream OpenRead(Uri address)
{
    Stream stream2;

    // --- removed for brevity ---

    WebRequest request = null;
    this.ClearWebClientState();
    try
    {
        request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address));
        Stream responseStream = (this.m_WebResponse = this.GetWebResponse(request)).GetResponseStream();

        // --- removed for brevity ---

        stream2 = responseStream;
    }
    catch (Exception exception)
    {

        // --- removed for brevity ---

        AbortRequest(request);
        throw exception;
    }
    finally
    {
        this.CompleteWebClientState();
    }
    return stream2;
}

... with ClearWebClientState() as follows:

private void ClearWebClientState()
{
    // --- removed for brevity ---

    this.m_WebResponse = null;
    this.m_WebRequest = null;
}
Community
  • 1
  • 1
Steve Guidi
  • 19,700
  • 9
  • 74
  • 90

1 Answers1

-2

To be sure that WebResponse's resources are released you can explicitly call Close method.

Here's modified ClearWebClientState method:

private void ClearWebClientState()
{
    // --- removed for brevity ---
    if ( this.m_WebResponse != null )
        this.m_WebResponse.Close();
    this.m_WebResponse = null;

    this.m_WebRequest = null;
}
Vadym Stetsiak
  • 1,974
  • 18
  • 22
  • Thank you for your response. I realize that `Close()` will release the resource, however the example I gave is from the decompiled implementation of the `System.Web.WebClient` type and I don't have the luxury of changing that :) – Steve Guidi Jun 14 '11 at 21:10