11
相關問題:WebClient in .Net not releasing socket resources如果在WebException中引發WebResponse引用,是否應從WebClient引發?
在調試資源泄漏的問題,我注意到,System.Net.WebException
(非一次性類型)包含了System.Net.WebResponse
參考(一次性類型)。我想知道在明確處理WebResponse
時是否應該處理該引用,如以下代碼片段所示。
using (WebClient client = new WebClient())
{
WebException ex = Assert.Throws<WebException>(() => client.OpenRead(myUri));
Assert.That(
((HttpWebResponse)ex.Response).StatusCode,
Is.EqualTo(HttpStatusCode.ServiceUnavailable));
}
的WebException.WebResponse
參考是在WebClient
現有的參考的副本。我認爲它將通過WebClient.Dispose
進行處理,但情況並非如此,因爲WebClient
不會覆蓋受保護的Component.Dispose(bool)
基本方法。事實上,反彙編表明,WebResponse
資源永遠不會被處置,而是在不再需要時被設置爲空。
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;
}
...與ClearWebClientState()
如下:
private void ClearWebClientState()
{
// --- removed for brevity ---
this.m_WebResponse = null;
this.m_WebRequest = null;
}
謝謝您的答覆。我意識到'Close()'會釋放資源,但是我給出的例子是來自'System.Web.WebClient'類型的反編譯實現,我沒有奢望改變:) – 2011-06-14 21:10:28