【问题标题】:How to break out of Parallel.ForEach within a Task如何在任务中突破 Parallel.ForEach
【发布时间】:2020-01-19 14:46:20
【问题描述】:

我正在运行 Parallel.ForEach 作为任务。我想在满足某个条件时摆脱它。考虑如下:

            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

如果totalCount > LimitedNumber,我如何尽早摆脱Parallel.ForEachTask

【问题讨论】:

    标签: .net task break parallel.foreach


    【解决方案1】:

    您可以通过在 sub 中作为变量传递来使用 ParallelLoopState 类。 Break 是一种对您的情况有用的方法。

           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
                ...........
                .........
    

    更多详情请咨询https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallelloopstate?view=netframework-4.8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2012-09-16
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多