1

How to pause and resume the parallel for each based on number of thread executed.

My requirement is I have a N time of loop count in each iteration I have request one API call .the max number of request is 2. i have to wait for any one the request is finished then i have to iterate next one. Please suggest how to pause and resume the parallel foreach loop

My code below,

var MaxConcurrency = new ParallelOptions() { MaxDegreeOfParallelism = 2 };

Parallel.ForEach(ListofWI, MaxConcurrency, async (CurrentWI) =>
{
    ServiceInput objServiceInput = new ServiceInput { Login = newLoginDetails,
        Connectioninfo = newConnectionInfo, WorkItem = CurrentWI.Value,
        Services = mlserviceList };

    String Inputstring = JsonConvert.SerializeObject(objServiceInput,
        Newtonsoft.Json.Formatting.Indented);

    WIuploader newUpload = new WIuploader(logininfo, CurrentWI.Value, newConnectionInfo);
    Progress<WorkItem> report = new Progress<WorkItem>(workItemUpdate =>
    {
    });
    workItem = await threadingtask.Task.Run(() => newUpload.Execute(report));
    StatusofWorkitem.Add(workItem);
});
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Natchatra
  • 29
  • 5
  • 3
    The `Parallel.ForEach` method does not support `async` delegates. See this question: [Parallel.ForEach and async-await](https://stackoverflow.com/questions/23137393/parallel-foreach-and-async-await). – Theodor Zoulias Jan 24 '23 at 14:15
  • Use an `ActionBlock` instead? – Fildor Jan 24 '23 at 14:44
  • 2
    I think you are already doing it, by setting: MaxDegreeOfParallelism = 2. This means you will only have max two parallel threads executing your requests at the same time. There is also no need to do: threadingtask.Task.Run as it is practically Parallel.foreach is for. Just execute your newUpload.Execute(report) without wrapping it into a async task. – Andrei Jan 24 '23 at 18:37

0 Answers0