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

2024-01-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 秒。所以,问题不在于网速。

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


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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一个进程的传出连接数限制(.Net) 的相关文章

随机推荐