.NET-如何使用信号灯将一段代码一次仅限制为200个线程 [英] .net - How to restrict a block of code to only 200 threads at a time using semaphoreslim
本文介绍了.NET-如何使用信号灯将一段代码一次仅限制为200个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开发了一个.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);
推荐答案
如何将SemaphoreSlim限制为在所有请求中仅使用200个线程(当多个用户或请求同时进入时)?
更改SemaphoreSlim
实例的作用域。
目前,代码为每个请求创建SemaphoreSlim
,因此每个请求被限制为200个并发请求。要让SemaphoreSlim
跨多个请求工作,您应该将其定义为在这些请求之间共享。要么将SemaphoreSlim
封装在注入了单例生存期的类型中,要么将SemaphoreSlim
声明为static
。
这篇关于.NET-如何使用信号灯将一段代码一次仅限制为200个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文