.net - .Net 中的 WebClient 不释放套接字资源

标签 .net resources

我在使用一些简单的测试代码时遇到了问题,这些代码从我们的一项 Restful 服务中进行批量下载。对 Dispose 的调用似乎没有释放低级套接字。这是基本代码;

foreach(...)
{
  using(WebClient client = new WebClient())
  {
    string results = client.DownloadString("http://host/request");
    client.Dispose();
  }
}

这会在 255 次循环后导致异常。我尝试添加这一行(通过另一个stackoverflow帖子的一些建议)。
System.Net.ServicePointManager.DefaultConnectionLimit = 500;

然后我在 500 次循环后得到一个异常。所以,在我看来,低级套接字连接没有被释放。

有没有其他人看到过这个问题?你知道一个解决方法。

谢谢

最佳答案

WebClient 不会覆盖 Dispose它继承自 Component .

应该不需要调用 Dispose 并且我没有收到您提到的错误。请提及其他 stackoverflow 帖子。

事实上,WebClient 不会保留任何需要处理的状态,并且是非常无状态的。查看 Reflector 中的实现,很明显它负责处理这里的资源(方法 DownloadDataInternal 是从 DownloadString 调用的):

private byte[] DownloadDataInternal(Uri address, out WebRequest request)
{
    byte[] buffer2;
    if (Logging.On)
    {
        Logging.Enter(Logging.Web, this, "DownloadData", address);
    }
    request = null;
    try
    {
        request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address));
        buffer2 = this.DownloadBits(request, null, null, null);
    }
    catch (Exception exception)
    {
        if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
        {
            throw;
        }
        if (!(exception is WebException) && !(exception is SecurityException))
        {
            exception = new WebException(SR.GetString("net_webclient"), exception);
        }
        AbortRequest(request);
        throw exception;
    }
    catch
    {
        Exception exception2 = new WebException(SR.GetString("net_webclient"), new Exception(SR.GetString("net_nonClsCompliantException")));
        AbortRequest(request);
        throw exception2;
    }
    return buffer2;
}

关于.net - .Net 中的 WebClient 不释放套接字资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4070503/

相关文章:

c# - X 已经包含 EntityFramework 的定义 Y? (简单数据库)

xcode - 用于向 Xcode 项目添加资源的命令行工具

android - 找不到与给定名称相匹配的资源 Android 1.6

java - 如何为 GlassFish Web 应用程序提供对外部资源(文件)的访问?

c# - 遍历嵌入式资源并复制到本地路径

c# - 想要使用XAML资源文件更改窗口颜色

.net - 嵌入 IronPython - 无法添加对系统的引用

.net - 在两个具有相同名称的 XSD 组之间进行选择

.net - 当 .NET 垃圾收集压缩堆时, "Allocate Bytes"性能计数器是否更新?

c# - iTextSharp - 移动 Acrofield