简体   繁体   中英

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. To test this I set up an endpoint that sleeps for 5 seconds and then returns.

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.

My question is...How do I limit the max connections using the asynchronous HttpClient?

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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