简体   繁体   English

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

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

When I download a file in one thread, it took 0.1 second. 当我在一个线程中下载文件时,花了0.1秒。 But when I download the same file in 100 threads - it took 10 seconds for each downloading. 但是,当我以100个线程下载同一文件时-每次下载花了10秒。 Source code: 源代码:

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);
}

Thus, if I run a program with 100 threads, speed 10 seconds per file. 因此,如果我运行一个具有100个线程的程序,则每个文件的速度为10秒。 But if I run the second program at the same time with 1 thread, speed 0.1 second per file. 但是,如果我同时使用1个线程运行第二个程序,则每个文件的速度为0.1秒。 So, problem is not in internet speed. 因此,问题不在互联网速度上。

Why the download speed goes down with increasing number of threads, but it does not affect the other process (the same file)? 为什么下载速度会随着线程数量的增加而降低,但是却不影响其他进程(同一文件)? How to increase the speed in one process? 如何在一个过程中提高速度?

1) You can adjust this parameter in your configuration file (default value is 2) : 1)您可以在配置文件中调整此参数(默认值为2):

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

2) In order to force your program to create several sockets, download from different application domains. 2)为了强制您的程序创建多个套接字,请从不同的应用程序域下载。

  1. There is only one network adapter. 只有一个网络适配器。 This could be your bottleneck 这可能是您的瓶颈
  2. Are you downloading from the same server? 您要从同一服务器下载吗? This could be a bottleneck 这可能是瓶颈
  3. Threads have a cost - switching between threads on a cpu (context switching) takes times and I doubt you have 100 cpus running. 线程有成本-在cpu上的线程之间切换(上下文切换)需要花费时间,我怀疑您正在运行100 cpus。

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

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