0
所以我正在處理記錄。我正在使用任務來處理每條記錄。 我的問題是我的程序在所有任務完成之前完成。 任何任何想法,我在做什麼錯在這裏?vb.net不等到所有任務完成
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
UPDATE
通過@HansPassant的建議和@usr
之所以不使用的foreach我已經通過任務列表解決了我的問題,是更多的紀錄可以在處理時添加..因此,儘管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
foreach比做更好的解決方案。我猜測它沒有捕捉任何東西。再次過程如何? – Claudius
我同意重新捕捉,(現有的代碼 - 我第一次看它),我會更新它。 – Fiona
很不清楚你如何編譯。您應該將任務的*數組*傳遞給WaitAll()。通過創建一個List(Of Task)開始解決這個問題。並且要注意LongRunning,如果你有超過幾十條記錄,那麼這臺機器會非常困難。 –