繁体   English   中英

一个进程的传出连接限制(.Net)

[英]Limit of outgoing connections for one process (.Net)

当我在一个线程中下载文件时,花了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秒。 因此,问题不在互联网速度上。

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

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

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

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

  1. 只有一个网络适配器。 这可能是您的瓶颈
  2. 您要从同一服务器下载吗? 这可能是瓶颈
  3. 线程有成本-在cpu上的线程之间切换(上下文切换)需要花费时间,我怀疑您正在运行100 cpus。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM