user2924019 user2924019 - 2 months ago 15
C# Question

How to stop a Parallel.ForEach loop?

I have this code to start a Parallel ForEach loop:

Parallel.ForEach<ListViewItem>(filesListView.Items.Cast<ListViewItem>(), new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, item => {
if (CallToStop == true)
{
//Code here to stop the loop!
}
internalProcessStart(item);
});


I have some code which will check if there is a call to stop the threads, and then I would like to
break;
the code, but this doesn't work with Parallel.

I found the same question by someone else, but their code is slighly different to mine, and I'm not sure where to put the
ParallelLoopState state
.

Thanks!

Answer

Rewrite as below

Parallel.ForEach<ListViewItem>(filesListView.Items.Cast<ListViewItem>(), new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, (item, state) => {
    if (CallToStop == true)
        {  
            state.Break();
        }        
    internalProcessStart(item);
});

Hope this helps.