0

I need to modify the below code to use a parallel.foreach loop vs a regular foreach loop.

The issue that I have is passing an object to to the foreach loop. I am new using parallel.foreach loop - does anyone have some info on this?

Current code

var objSellerPeramaterValuesList = objInboundDB.GetMwsRequestParameters();

foreach (SellerModel objSellerPeramaterValues in objSellerPeramaterValuesList)
{
    Method.InsertProcessLog(new ProcessLogModel
                                {
                                    sProcessName = sProcessName,
                                    sSellerID = objSellerPeramaterValues.sSellerId,
                                    sStartDate = sProcessStartDate,
                                    sEndDate = sProcessEndDate,
                                    sStatus = "STARTED",
                                    sMessage = "Started Process For ID .. " + objSellerPeramaterValues.sSellerId
                                });

    // more code here......
}

The issue with this is that the list will contain 3000+ items and the loop will loop through each item, I need to run them all in parallel.

So I want to use the Parallel.foreach function but I can't get it to work by passing the object.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
abe
  • 11

1 Answers1

1

It looks like you should just be able to do:

Parallel.ForEach(objSellerPeramaterValuesList, objSellerPeramaterValues =>
{
    /* exact same code */
    // Method.InsertProcessLog(...) // etc
});

However, you're going to have to be very mindful of the ordering, and concurrency - if anything you're doing (including components/tools you're using) isn't/aren't designed to be thread-safe: bad things.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • but the set variables returned by the underlying process will be local to each job, am i correct? – abe Mar 22 '21 at 21:12
  • @abe what exactly do you mean by "the set variables returned by the underlying process"? Details matter hugely, and in these scenarios it is annoyingly necessary to be obsessively specific to the point of pedantry – Marc Gravell Mar 23 '21 at 00:04
  • thanks for your help all is working fine i had some issue and it look like it was a code issue because of the loop however it was a data issue and the job failed with a good error , but the parallel process works fine, i tried it with subset and it worked as expected. – abe Mar 23 '21 at 16:33
  • is there a way if one thread failed for him to exit the loop and stop processing while others continue. – abe Mar 24 '21 at 17:52
  • to be more precise, i need to connect to a server based on the ID i get and do work after we connect. I know i can do the connection in a try catch the process will move on, however in this case for this Item i want to stop the loop and not continue but the others should continue , is it possible or do i have to continue the whole code with multiple try catch in it – abe Mar 24 '21 at 17:55