简体   繁体   English

如何使用Async HttpClient C#限制连接

[英]How to limit connections with Async HttpClient C#

I am trying to limit the number of max connections i have to an endpoint and I am doing this by setting ServicePointManager.DefaultConnectionLimit but it is not working. 我试图限制到端点的最大连接数,我通过设置ServicePointManager.DefaultConnectionLimit来做到这一点,但它不起作用。 To test this I set up an endpoint that sleeps for 5 seconds and then returns. 为了测试这一点,我设置了一个休眠5秒然后返回的端点。

Here is my code: 这是我的代码:

class Program
{
    private static Uri uri = new Uri("http://myservice.com?sleepForMillisecond=5000"));

    static void Main(string[] args)
    {
        ServicePointManager.DefaultConnectionLimit = 1;
        MainAsync().Wait();
    }

    static async Task MainAsync()
    {
        var watch = Stopwatch.StartNew();
        var tasks = new List<Task>()
            {
                Task.Run(async () => await MakeCallWithHttpClient()),
                Task.Run(async () => await MakeCallWithHttpClient()),
                Task.Run(async () => await MakeCallWithHttpClient())
            };

        await Task.WhenAll(tasks);
        watch.Stop();
        Console.WriteLine("Elapsed Time For HttpClient: " + watch.Elapsed);

        watch.Restart();
        tasks = new List<Task>()
            {
                Task.Run(async () => await MakeCallWithWebClient()),
                Task.Run(async () => await MakeCallWithWebClient()),
                Task.Run(async () => await MakeCallWithWebClient())
            };

        await Task.WhenAll(tasks);
        watch.Stop();
        Console.WriteLine("Elapsed Time For WebClient: " + watch.Elapsed);
        Console.WriteLine("Press Enter To Exit.");
        Console.ReadLine();
    }

    private static async Task MakeCallWithHttpClient()
    {
        var client = new HttpClient();
        await client.GetStringAsync(uri);
        Console.WriteLine("Done");
    }

    private static async Task MakeCallWithWebClient()
    {
        var client = new WebClient();
        await client.DownloadStringTaskAsync(uri);
        Console.WriteLine("Done");
    }
} 

Below is the output: 以下是输出:

Done
Done
Done
Elapsed Time For HttpClient: 00:00:05.0953943
Done
Done
Done
Elapsed Time For WebClient: 00:00:15.0450096

As you can see the async HttpClient is not limited by the max connections of 1 since making 3 calls in parallel takes 5 seconds and the async WebClient is limited by the 1 connection since making 3 calls in parallel takes 15 seconds. 如您所见,异步HttpClient不受最大连接数1的限制,因为并行进行3个调用需要5秒,而异步WebClient受到1连接的限制是因为并行进行3个调用需要15秒。

My question is...How do I limit the max connections using the asynchronous HttpClient? 我的问题是...如何使用异步HttpClient限制最大连接数?

Thanks. 谢谢。

对所有请求使用相同的HttpClient实例,连接限制将按预期工作。

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

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