【问题标题】:Limit of outgoing connections for one process (.Net)一个进程的传出连接限制 (.Net)
【发布时间】:2013-10-04 11:44:02
【问题描述】:

当我在一个线程中下载文件时,需要 0.1 秒。但是当我在 100 个线程中下载相同的文件时 - 每次下载需要 10 秒。源代码:

private static int _threadsCount;
private static string _url;

private static void Main(string[] args)
{
    _url = ConfigurationManager.AppSettings["Url"];

    int threadsLimit = 1;

    if (0 != args.Length)
        threadsLimit = int.Parse(args[0]);

    for (int i = 0; i < threadsLimit; i++)
    {
        var thread = new Thread(Start);
        thread.Start();
    }

    while (_threadsCount < threadsLimit)
    {
        Thread.Sleep(1000);
    }

    Console.WriteLine("Done");
}

static void Start()
{
    var webClient = new WebClient();

    var stopwatch = new Stopwatch();
    stopwatch.Reset();

    stopwatch.Start();

    for (int i = 1; i <= 10; i++)
    {
        webClient.DownloadData(_url);
    }

    stopwatch.Stop();

    Console.WriteLine(stopwatch.ElapsedMilliseconds);

    Interlocked.Increment(ref _threadsCount);
}

因此,如果我运行一个有 100 个线程的程序,每个文件的速度为 10 秒。但是,如果我 同时运行第二个程序,使用 1 个线程,每个文件的速度为 0.1 秒。所以,问题不在于网速。

为什么下载速度随着线程数的增加而下降,但不影响其他进程(同一个文件)?如何提高一个进程的速度?

【问题讨论】:

  • 完成的总时间变化很大吗?

标签: .net networking limit


【解决方案1】:

1) 您可以在配置文件中调整此参数(默认值为 2):

<system.net>
    <connectionManagement>
        <add address="*" maxconnection="2" />
    </connectionManagement>
</system.net>

2) 为了强制您的程序创建多个套接字,请从不同的应用程序域下载。

【讨论】:

    【解决方案2】:
    1. 只有一个网络适配器。这可能是您的瓶颈
    2. 您是否从同一服务器下载?这可能是一个瓶颈
    3. 线程有成本 - 在 cpu 上的线程之间切换(上下文切换)需要时间,我怀疑你有 100 个 cpu 在运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多