I am using httptrigger function in dotnet core where i am getting httprequest data in Json format.I need to insert this value in Google Merchant center account. There are almost 9000 rows (dynamic data each time) that needs to be inserted. How i can implement the Parallel.for logic which will execute faster. Currently i am using for each loop like below but it is taking more time. Below is the code.
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic body = JsonConvert.DeserializeObject(requestBody);
for (int i =0;i<body.Count;i++)
{
Product newProduct = InsertProduct(merchantId, websiteUrl,body[i]);
}
I created a small example maybe there you can find the best way which fits your case best.
dotnet fiddle Example
There are 3 options:
In sequence
As the title says every item is processed in sequence. Very save method but not the fastest one to process 9000 items :)
With Parallel.For Library
Like said from the comments its good for CPU bound processing but has some lacks on async methods (here)
With Async-Await
I think in your example this fits best for you. Every item is processed in parallel, starts the processing directly and spinns up a
Task
. (Copied the async-extension from here)...Updated
Thanks for the comments. I have updated the async-await implementation to a more simpler one:
And also added the
MAX_DEGREE_OF_PARALLELISM
set to 1. This has a huge impact on the parallel processing like described in the commends.