【发布时间】:2016-03-10 13:14:40
【问题描述】:
所以我正在处理记录。我正在使用任务来处理每条记录。 我的问题是我的程序在所有任务完成之前完成。 有人对我在这里做错了什么有任何想法吗?
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
【问题讨论】:
-
foreach 是比这样做更好的解决方案。我猜它什么也抓不到。流程又是怎样的?
-
我同意重新捕获,(现有代码 - 我第一次看到它),我会更新它。
-
很不清楚你是如何编译的。您应该将任务的array 传递给WaitAll()。通过创建一个 List(Of Task) 开始解决这个问题。并且要小心 LongRunning,如果你有超过几十条记录,它会非常猛烈地撞击机器。
-
好的。谢谢你的帮助。我会调查一下。
-
@HansPassant 他正在使用参数重载。常见错误。