Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a Parallel.ForEach loop?

Tags:

c#

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!

like image 973
user2924019 Avatar asked May 14 '26 08:05

user2924019


1 Answers

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.

like image 153
Cinchoo Avatar answered May 15 '26 22:05

Cinchoo