SemaphoreSlim 限制并发请求

SemaphoreSlim

可限制并发请求数,通过WaitAsync()方法等待信号量,如果当前正在进行的请求数已经达到最大并发数,则会被阻塞,直到有请求完成并释放信号量。每个请求处理完成后,通过Release()方法释放一个信号量,使得其他请求可以执行。通过这种方式可以控制请求的并发数量,并且保证请求之间不会互相阻塞。

举个httpclient的应用例子

using System.Net.Http;
using System.Threading;

public class HttpClientManager
{
    // 最大并发数
    private const int MAX_CONCURRENT_REQUESTS = 10;

    // 信号量
    private static readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(MAX_CONCURRENT_REQUESTS);

    // HttpClient实例
    private static readonly HttpClient httpClient = new HttpClient();

    // 发送HTTP GET请求
    public static async Task<string> SendGetRequestAsync(string url)
    {
        await semaphoreSlim.WaitAsync();  // 等待信号量

        try
        {
            HttpResponseMessage response = await httpClient.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }
        finally
        {
            semaphoreSlim.Release();  // 释放信号量
        }
    }

    // 发送HTTP POST请求
    public static async Task<string> SendPostRequestAsync(string url, IEnumerable<KeyValuePair<string, string>> parameters)
    {
        await semaphoreSlim.WaitAsync();  // 等待信号量

        try
        {
            HttpContent httpContent = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
            return await response.Content.ReadAsStringAsync();
        }
        finally
        {
            semaphoreSlim.Release();  // 释放信号量
        }
    }
}
posted @ 2023-04-27 10:49  C余L小R鱼  阅读(182)  评论(0编辑  收藏  举报