【问题标题】:.net - How to restrict a block of code to only 200 threads at a time using semaphoreslim.net - 如何使用 semaphoreslim 将代码块一次限制为 200 个线程
【发布时间】:2020-11-30 01:57:48
【问题描述】:

我已经开发了一个 .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);

【问题讨论】:

    标签: .net-core concurrency parallel-processing semaphore


    【解决方案1】:

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

    更改SemaphoreSlim 实例的范围。

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

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多