簡體   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