2011-03-30 58 views
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; 
} 

回答

-2

要確保WebResponse類的資源被釋放,你可以顯式調用Close方法。

這裏的修改ClearWebClientState方法:

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

    this.m_WebRequest = null; 
} 
+0

謝謝您的答覆。我意識到'Close()'會釋放資源,但是我給出的例子是來自'System.Web.WebClient'類型的反編譯實現,我沒有奢望改變:) – 2011-06-14 21:10:28

相關問題