使用`semaphoreslim`配合`httpclient`的异步方法可以精确限制同时在途请求的数量。通过调用`waitasync()`获取许可,并在`finally`块中调用`release()`释放许可,既能保证并发上限,又能确保异常情况下不会死锁。

SemaphoreSlim如何控制并发度并处理超时?
SemaphoreSlim是C#中用于控制并发访问的理想工具。构造函数中的参数直接定义了最大同时运行的任务数。在异步循环中,每个任务必须先等待信号量可用,这会自动将超出限制的任务挂起。如果设置了超时时间,当等待超时时会抛出OperationCanceledException,开发者可以根据需要捕获该异常以记录日志或重试。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ConcurrentPostDemo
{
public class Program
{
private static readonly HttpClient _httpClient = new HttpClient();
public static async Task Main()
{
// 定义要发送的请求数据
var urls = new List<string>
{
"https://api.example.com/submit",
"https://api.example.com/submit",
"https://api.example.com/submit"
};
// 设置最大并发数为3
int maxConcurrency = 3;
using var semaphore = new SemaphoreSlim(maxConcurrency);
var tasks = new List<Task>();
foreach (var url in urls)
{
tasks.Add(ProcessRequest(url, semaphore));
}
await Task.WhenAll(tasks);
Console.WriteLine("所有请求处理完毕。");
}
private static async Task ProcessRequest(string url, SemaphoreSlim semaphore)
{
await semaphore.WaitAsync();
try
{
Console.WriteLine($"开始请求: {url}, 当前并发: {maxConcurrency - semaphore.CurrentCount}");
var response = await _httpClient.PostAsync(url, null);
Console.WriteLine($"响应状态: {response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($"请求失败: {ex.Message}");
}
finally
{
semaphore.Release();
}
}
}
}
如何处理请求失败与资源清理?
在批量发送请求时,网络波动或服务器错误是常态。必须在try-finally结构中确保Release()被调用,否则信号量计数会永久减少,导致后续任务无法获取许可而卡死。对于单个请求的失败,不应中断整个批次的处理,而是应记录错误并继续执行其他任务。此外,HttpClient实例应当复用,避免频繁创建销毁导致的端口耗尽问题。

// 验证失败处理的代码片段
private static async Task SafeProcessRequest(string url, SemaphoreSlim semaphore)
{
await semaphore.WaitAsync();
try
{
// 模拟可能失败的请求
if (url.Contains("error"))
throw new HttpRequestException("Simulated Error");
await _httpClient.GetAsync(url);
}
catch (Exception)
{
// 记录日志,但不重新抛出,以免中断流程
Console.WriteLine("Handled error for " + url);
}
finally
{
// 无论成功还是失败,都必须释放信号量
semaphore.Release();
}
}
当请求体包含大量数据时,内存占用如何变化?
虽然SemaphoreSlim限制了并发数,但如果每个请求都加载巨大的请求体到内存中,仍可能导致内存峰值过高。在C#中,建议使用StreamContent或ByteArrayContent来管理大体积数据,并确保在请求完成后及时释放相关资源。同时,监控GC的压力,必要时调整垃圾回收的模式。


















