What would be the most effective way to pause and stop (before it ends) parallel.foreach?
Parallel.ForEach(list, (item) =>
{
doStuff(item);
});
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Damien_The_Unbeliver has a good method, but that is only if you want to have some outside process stop the loop. If you want to have the loop break out like using a
breakin a normalfororforeachloop you will need to use a overload that has aParallelLoopStateas one of the parameters of the loop body.ParallelLoopStatehas two functions that are relevant to what you want to do,Stop()andBreak().The function
Stop()will stop processing elements at the system’s earliest convenience which means more iterations could be performed after you call Stop() and it is not guaranteed that the elements that came before the element you stopped at have even begun to process.The function
Break()performs exactly the same asStop()however it will also evaluate all elements of theIEnumerablethat came before the item that you calledBreak()on. This is useful for when you do not care what order the elements are processed in, but you must process all of the elements up to the point you stopped.Inspect the ParallelLoopResult returned from the foreach to see if the foreach stopped early, and if you used
Break(), what is the lowest numbered item it processed.Here is a more practical example
No matter how it splits up the work it will always return 2 as an answer.
let’s say the processor dispatches two threads to process this, the first thread processes elements 0-2 and the 2nd thread processes elements 3-5.
Now the lowest index Break was called from was 2 so
ParallelLoopResult.LowestBreakIterationwill return 2 every time, no-matter how the threads are broken up as it will always process up to the number 2.Here an example how how Stop could be used.
Depending how it splits up the work it will either return 2 or 4 as the answer.
let’s say the processor dispatches two threads to process this, the first thread processes elements 0-2 and the 2nd thread processes elements 3-5.
In this case it will return 4 as the answer. Lets see the same process but if it processes every other element instead of 0-2 and 3-5.
This time it will return 2 instead of 4.