英文:
Limit number of Threads without waiting for them
问题
我有一个用于向GRPC API发送数据的foreach循环。我希望我的循环能够同时发送多个请求,但限制请求数量,例如10个。我当前的代码如下:
foreach (var element in elements)
{
var x = new Thread(() =>
SendOverGrpc(element));
x.Start();
}
但是,使用这段代码,软件会“立即”发送所有请求。如何限制请求数量,例如10个?一旦我的10个请求中的一个完成,我想发送下一个请求。
英文:
I have a foreach loop that sends data to a GRPC API. I want my loop to send multiple requests at the same time but limit the number of requests to e.g. 10. My current code is the following:
foreach (var element in elements)
{
var x = new Thread(() =>
SendOverGrpc(element));
x.Start();
}
But with that code, the software "immediately" sends all requests. How can I limit the number of requests to e.g. 10? As soon as one of my 10 requests is finished, I want to send the next one.
答案1
得分: 2
Easiest way is Parallel.Foreach, eg
Parallel.ForEach(elements, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, element => {
SendOverGrpc(element);
});
英文:
Easiest way is Parallel.Foreach, eg
Parallel.ForEach(elements, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, element =>
{
SendOverGrpc(element);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论