【发布时间】:2020-11-04 17:05:31
【问题描述】:
我在向 .NET Core Web 服务发送大量请求时遇到问题。我正在使用 SemaphoreSlim 来限制同时请求的数量。当我收到 10061 错误(Web 服务拒绝连接)时,我想回拨同时请求的数量。我目前的想法是取消引用 SemaphoreSlim 并创建另一个:
await this.semaphoreSlim.WaitAsync().ConfigureAwait(false);
counter++;
Uri uri = new Uri($"{api}/{keyProperty}", UriKind.Relative);
string rowVersion = string.Empty;
try
{
HttpResponseMessage getResponse = await this.httpClient.GetAsync(uri).ConfigureAwait(false);
if (getResponse.IsSuccessStatusCode)
{
using (HttpContent httpContent = getResponse.Content)
{
JObject currentObject = JObject.Parse(await httpContent.ReadAsStringAsync().ConfigureAwait(false));
rowVersion = currentObject.Value<string>("rowVersion");
}
}
}
catch (HttpRequestException httpRequestException)
{
SocketException socketException = httpRequestException.InnerException as SocketException;
if (socketException != null && socketException.ErrorCode == PutHandler.ConnectionRefused)
{
this.semaphoreSlim = new SemaphoreSlim(counter * 90 / 100, counter * 90 / 100);
}
}
}
finally
{
this.semaphoreSlim.Release();
}
如果我这样做,在我刚刚取消引用的信号量上等待的其他任务会发生什么?我的猜测是,在对象被垃圾收集和处置之前,什么都不会发生。
【问题讨论】:
标签: .net-core httpclient semaphore