信号量.NET中应指定什么MaxCount?
我正在使用信号量来避免汇总Exception(任务已取消),并使用处理器将其视为最大值。
int processorCount = Environment.ProcessorCount;
var semaphore = new SemaphoreSlim(maxCount: processorCount, initialCount: processorCount);
但是在这种情况下,它正在缓慢运行(我正在提出1000个I/O请求,但是请求的数量可能会增加10 000,因此需要确保我不会有错误,并且我正在阅读来自REDIS,所有副作用需要4.5秒),我应该使用ThreadPool中的可用线程,还是在发出异步I/O请求时用作最大值的良好习惯?
I'm using semaphore to avoid AggregateException (Task was cancelled) and using processors count as a maxCount.
int processorCount = Environment.ProcessorCount;
var semaphore = new SemaphoreSlim(maxCount: processorCount, initialCount: processorCount);
But in this case it's running slowly (I'm making 1000 of I/O requests, but number of requests could increase up to 10 000 so need to be sure that I will don't have error, and I'm reading data from Redis and it takes 4,5 seconds with all side work), should I use available threads from threadpool or what value is a good practice to use as a maxCount when making asynchronous I/O requests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在I/O-BOND工作中做异步工作。您的代码正在“等待”的工作,例如Redis的响应。在这个“等待”的时间中,您可以像其他异步请求一样做其他工作。
因此,这意味着异步工作不直接绑定到您的处理器计数(是间接的),因为它可以在“等待”时处理更多的异步请求。更多的工作取决于您正在做的异步工作,硬件,延迟等。最好的是尝试一下每个线程可以处理多少。
我通常从MaxCount = 20开始,这是非常安全的。我经常成功地进入MaxCount = 50没有任何问题。
因为它仍然间接绑定到处理器线程,但是您不知道每个线程可以做多少工作,所以我使用处理器计数的乘数。
因此,我使用环境。然后,我实验将乘数增加到 6 或 8 。
You do async work for I/O-bound work. Work that your code is "waiting" for, such as a response from Redis. In this "waiting" time you can do other work, like other async requests.
So, this means async work is not directly bound to your processor count (it is indirectly), because it can handle more async requests when "waiting". How much more work depends on the async work you are doing, hardware, latency, etc. The best is to experiment with how much you can handle per thread.
I usually start with maxCount=20, which is very safe. I often succeed in going to maxCount=50 without any problems.
Because it's still indirectly bound to processor threads, but you don't know how much work you can do per thread, I use a multiplier of processor counts.
So I use Environment.ProcessorCount * 4. Then I experiment in increasing the multiplier to 6 or 8.