当不断有多个调用者等待进入时,SemaphoreSlim 是否保证进入
Does SemaphoreSlim guarantee entry when there are constantly more than one callers waiting for entry
假设我有一个 SemaphoreSlim 限制对外部 API 的并发调用,如下所示:
private static readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(10);
public async Task<HttpResponseMessage> SendApiRequest(HttpRequestMessage request)
{
using (await semaphoreSlim.WaitAsync())
return await SendRequestToAPI(request);
}
如果API的来电数量没有长时间等待的来电者,但仍然至少有两个来电者一直在等待,是否保证所有来电者都被允许通过最终?或者一个请求可以是 "unlucky" 并且当另一个调用者释放信号量时永远不会被选择进入?
根据 documentation:
If multiple threads are blocked, there is no guaranteed order, such as
FIFO or LIFO, that controls when threads enter the semaphore.
所以是的,一个请求可能是不幸的,永远不会被选中。
假设我有一个 SemaphoreSlim 限制对外部 API 的并发调用,如下所示:
private static readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(10);
public async Task<HttpResponseMessage> SendApiRequest(HttpRequestMessage request)
{
using (await semaphoreSlim.WaitAsync())
return await SendRequestToAPI(request);
}
如果API的来电数量没有长时间等待的来电者,但仍然至少有两个来电者一直在等待,是否保证所有来电者都被允许通过最终?或者一个请求可以是 "unlucky" 并且当另一个调用者释放信号量时永远不会被选择进入?
根据 documentation:
If multiple threads are blocked, there is no guaranteed order, such as FIFO or LIFO, that controls when threads enter the semaphore.
所以是的,一个请求可能是不幸的,永远不会被选中。