限制线程数量,无需等待它们。

huangapple go评论64阅读模式
英文:

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);
    });

huangapple
  • 本文由 发表于 2023年2月16日 06:15:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定