Limit number of Threads without waiting for them

Advertisements

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.

>Solution :

Easiest way is Parallel.Foreach, eg

Parallel.ForEach(elements, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, element  =>
    {
      SendOverGrpc(element);
    });

Leave a ReplyCancel reply