vb.net不等到所有任务完成

时间:2016-03-10 13:14:40

标签: vb.net task

所以我正在处理记录。我正在使用任务来处理每条记录。 我的问题是我的程序在所有任务完成之前完成。 有人对我在这里做错了什么想法吗?

        Dim task As Task

        Try
            'Keep looping until no more requests to run have been made            
            Do
                Dim controller As New Controller()
                Dim record As Record = controller.GetNextRecord()

                If record IsNot Nothing Then

                    'Use Task!
                     task = Task.Factory.StartNew(Sub() controller.ProcessRecord(record), TaskCreationOptions.LongRunning)
                     CalledWhenBusy = True
                End If
        TryAgain:
            Loop Until ProcessAgain() = False


        Catch ex As System.Net.WebException
            logger.ErrorException("unable to connect to remoting server", ex)

        Finally
            logger.Info("Processed all records.. now about to wait for all tasks to complete")
            'Wait till all tasks have stopped running
            Task.WaitAll(task)

            logger.Info("Processed all records.. All tasks have completed")
            'The dispatcher has finished for now so clean up
            Me.StopUsing()
        End Try




Private Function ProcessAgain() As Boolean

    If CalledWhenBusy Then
        'Reset the flag and exit with true
        CalledWhenBusy = False
        Return True
    End If

    Return False

End Function

更新

我已经通过使用@HansPassant和@usr

建议的任务列表解决了我的问题

不使用Foreach的原因是在处理时可以添加更多记录..因此do while循环...

感谢您的帮助。

            Dim taskList = New List(Of Task)()

        Try
            'Keep looping until no more requests to run have been made            
            Do
                Dim controller As New Controller()
                Dim record As Record = controller.GetNextRecord()

                If record IsNot Nothing Then

                    'Use Task!
                    taskList.Add(Task.Factory.StartNew(Sub() controller.ProcessRecord(record)))
                    CalledWhenBusy = True
                End If
TryAgain:
            Loop Until ProcessAgain() = False


        Catch ex As System.Net.WebException
            logger.ErrorException("unable to connect to remoting server", ex)

        Finally
            logger.Info("Processed all records.. now about to wait for all tasks to complete")
            'Wait till all tasks have stopped running
            Task.WaitAll(taskList.ToArray())

            logger.Info("Processed all records.. All tasks have completed")
            'The dispatcher has finished for now so clean up
            Me.StopUsing()
        End Try

1 个答案:

答案 0 :(得分:2)

Task.WaitAll(task)正在等待一项任务。其他人在哪里?你有没有存放它们?从这段代码中看不出来。

理想情况下,您可以转换此代码,以便它可以使用Parallel.ForEach。您需要将工作项放入IEnumerable格式才能生效。例如,将它们添加到List并将列表提供给Parallel.ForEach