0

I am running a Parallel.ForEach as a task. I'm wanting to break out of it when a certain condition is met. Consider below:

            Dim opt As System.Threading.Tasks.ParallelOptions = New System.Threading.Tasks.ParallelOptions With {
                .MaxDegreeOfParallelism = My.Settings.ssUserMaxThreads}

            Dim ttask = Task.Factory.StartNew(Sub()

                                                  Parallel.ForEach(filesList, opt,
                                                    Sub(rom As String)

                                                        ProcessROM(rom, romDS, ClassHash)

                                                        totalCount += 1
                                                        Debug.WriteLine("TotalCount: " & totalCount)

                                                        If totalCount > LimitedNumber Then
                                                            Debug.WriteLine("Limited number exceeded")
                                                            'What here?
                                                        End If

                                                        con.Invoke(CType(Sub()
                                                                             ReportProgress()
                                                                         End Sub, Action))

                                                        Application.DoEvents()

                                                    End Sub
                                                    )

                                              End Sub)

            Do Until totalCount > LimitedNumber
                Application.DoEvents()
            Loop

How do I break out of this Parallel.ForEach OR Task early if totalCount > LimitedNumber?

stigzler
  • 793
  • 2
  • 12
  • 29

1 Answers1

0

You can make use of ParallelLoopState class by passing as a variable inside sub. Break is a method that is useful in your case.

       Parallel.ForEach(filesList, opt, Sub(rom As String, state as ParallelLoopState)
                        ProcessROM(rom, romDS, ClassHash)

                        .........
                        .........
                        If totalCount > LimitedNumber Then
                        Debug.WriteLine("Limited number exceeded")
                          state.Break();
                        End If
            ...........
            .........

For more details refer https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallelloopstate?view=netframework-4.8