我有以下异步方法,等待每行babsis上的单独方法。我不能为我的生活弄清楚如何把它带到一个新的水平,并等待整个数据表进行处理(即所有行开始一起开始,而不是一次开始)。任何帮助将不胜感激。
Public Async Function GetLabResultPanelPackByPRN_Async(ByVal ClientID As Integer, ByVal PRN As Integer, ByVal SamplePointID As Integer, ByVal StartDate As DateTime, ByVal EndDate As DateTime, ByVal InequalityMode As InequalityModes) As Task(Of List(Of LabResultPanelPack))
Dim LRPPs As New List(Of LabResultPanelPack)
Dim ta As New eniCIP_DataTableAdapters.proc_WebPortal_ResultsByPRNTableAdapter
Dim dt As New eniCIP_Data.proc_WebPortal_ResultsByPRNDataTable
ta.Fill(dt, PRN)
For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
Dim LRPP As New LabResultPanelPack
LRPP.LabResult = GetLabResultByPRNFromRow(row, InequalityMode)
Dim ResultsByDetAndSPTask As Task(Of List(Of LabResultExtended)) = GetResultsByDetAndSP_Async(ClientID, SamplePointID, row.lDetID, StartDate, EndDate, InequalityMode)
Dim ResultsBySampleTypeAndDetTask As Task(Of List(Of LabResultExtended)) = GetResultsBySampleTypeAndDet_Async(ClientID, row.lSampleTypeID, row.lDetID, StartDate, EndDate, InequalityMode)
Dim ResultsBySampleTypeGroupAndDetTask As Task(Of List(Of LabResultExtended)) = GetResultsBySampleTypeGroupAndDet_Async(ClientID, row.lSampleTypeGroupID, row.lDetID, StartDate, EndDate, InequalityMode)
LRPP.HistoricResultsByDetAndSP = Await ResultsByDetAndSPTask
LRPP.HistoricResultsByDetAndSampleType = Await ResultsBySampleTypeAndDetTask
LRPP.HistoricResultsByDetAndSampleTypeGroup = Await ResultsBySampleTypeGroupAndDetTask
LRPPs.Add(LRPP)
Next
Return LRPPs
End Function
答案 0 :(得分:2)
在这种情况下,解决方案只是简单地添加一个功能,并快速清理。
如果您创建一个新函数来处理一个行的处理,如下所示:
Private Async Function ProcessRow(row As YourRowType, ...) As Task(Of LabResultPanelPack)
Dim LRPP As New LabResultPanelPack
LRPP.LabResult = GetLabResultByPRNFromRow(row, InequalityMode)
'Add your tasks for processing the row further
Return LRPP
End Function
现在你的主循环看起来像这样:
For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
Dim LRPP = Await ProcessRow(row, ...)
LRPPs.Add(LRPP)
Next
此时您可以将LRPPs
列表更改为
Dim LRPPTasks As New List(Of Task(Of LabResultPanelPack))
将你的循环改为
For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
Dim LRPPTask = ProcessRow(row, ...)
LRPPTasks.Add(LRPPTask)
Next
这样,您就可以避免等待每一行,并在达到await
函数内的第一个ProcessRow
时继续处理行。
最后你需要做的就是改变你的回归
Return Await Task.WhenAll(LRPPTasks)
你已经完成了。
只是一个小小的补充:按照我的建议重写代码后,您最终会得到Await
中唯一的Function
。这意味着您可以从函数中删除Async
标记,从Await
删除Return
。通过这种方式,您可以减少开销。