.net - 如果从 WebClient 引发,是否应该处理 WebException 中的 WebResponse 引用?

标签 .net httpwebrequest webclient dispose httpwebresponse

相关问题:WebClient in .Net not releasing socket resources

在调试资源泄漏问题时,我注意到 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不会覆盖 protected Component.Dispose(bool)基法。事实上,拆解表明WebResponse资源永远不会被处理,而是在不再需要时设置为 null。
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;
}

最佳答案

要确保释放 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;
}

关于.net - 如果从 WebClient 引发,是否应该处理 WebException 中的 WebResponse 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489955/

相关文章:

c# - 嵌套查询的 StackOverflowException,小项目计数

c# - 通过代码(C# 或 PowerShell)获取有关进程(如 Sysinternals Process Explorer)的 .NET 程序集信息

.net - 从平面数据库结果集填充对象层次结构的最佳实践?

ssl - HttpWebRequest SSL 授权表

c# - Parallel.ForEach 中的 WebClient.DownloadFile()

c# - Web 客户端使用下载文件从服务器抓取文件 - 处理异常

C# - 从异步方法回调更新变量 BY REF - WebClient 类

.net - 在 WPF : Children. 中移除或 Children.Clear 不会释放对象

c# - HttpClientHandler/请求被中止 : Could not create SSL/TLS secure channel

asp.net - 处理来自 HttpWebRequest.GetResponse 的错误