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;
}