.net - 如何使用 semaphoreslim 将代码块一次限制为 200 个线程

.net - How to restrict a block of code to only 200 threads at a time using semaphoreslim

我开发了一个 .net 核心 Web API 并且有一个场景,我有大约 1000 条记录的列表,其中每条记录将被循环并调用第三方 api。第三方有一个限制API,只能同时发送200个请求。因此,我使用了 SemaphoreSlim 并将使用此代码块的线程数限制为 200,并且工作正常。

当多个用户或多个请求进入此端点时,第三方 api 会抛出错误。

如何限制 SemaphoreSlim 在所有请求中仅使用 200 个线程(当多个用户或请求同时进入时)?

SemaphoreSlim _concurrencySemaphoreForDescartesCall = new SemaphoreSlim(1,200);
    
    List<Task<searchDetailsViewModel>> searchList = new List<Task<searchDetailsViewModel>>(searchCriteriaList.Count);
        foreach (var criteria in searchCriteriaList)
        {
            await _concurrencySemaphore.WaitAsync();
            searchList.Add(Task.Run<searchDetailsViewModel>(async () =>
            {
                searchDetailsViewModel searchResults = new searchDetailsViewModel();
                try
                {
                    searchResults.searchResults = await AsncCall(criteria);
                }
                catch (Exception)
                {
                    searchResults.ErrorMessage = "There was a problem performing the s search.";
                }
                finally
                {
                    // here we release the throttler immediately
                    _concurrencySemaphore.Release();
                }
        
                return searchResults;
            }, cancellationToken));
        }
        
        searchDetailsViewModel[] searchResultsList = await Task.WhenAll(searchList);

How can I restrict the SemaphoreSlim to use only 200 threads across all the requests (when multiple users or requests come in at the same time)?

更改 SemaphoreSlim 实例的范围。

目前,代码为每个请求创建一个 SemaphoreSlim,因此每个请求限制为 200 个并发请求。要让 SemaphoreSlim 跨多个请求工作,您应该将其定义为在这些请求之间共享。要么将 SemaphoreSlim 封装在一个以单例生命周期注入的类型中,要么将 SemaphoreSlim 声明为 static.