下面的示例为计算订单总价的Order Detail对象创建并启动了一个Task,Task被添加到一个列表(List)中,后面的代码循环检索List中的结果,如果我需要一个未计算的结果,第二个循环将会暂停,直到Task完成。
Dim CalcTask As System.Threading.
Tasks.Task(Of Decimal)
Dim CalcTasks As New List(Of System.
Threading.Tasks.Task(Of Decimal))
For Each ord As Order_Detail In le.Order_Details
Dim od As Order_Detail = ord
CalcTask = System.Threading.
Tasks.Task(Of Decimal).
Factory.StartNew(Function() CalcValue(od))
CalcTasks.Add(CalcTask)
Next
Dim totResult As Decimal
For Each ct As System.Threading.Tasks.Task(Of Decimal) In CalcTasks
totResult += ct.Result
Next
Tasks.Task(Of Decimal)
Dim CalcTasks As New List(Of System.
Threading.Tasks.Task(Of Decimal))
For Each ord As Order_Detail In le.Order_Details
Dim od As Order_Detail = ord
CalcTask = System.Threading.
Tasks.Task(Of Decimal).
Factory.StartNew(Function() CalcValue(od))
CalcTasks.Add(CalcTask)
Next
Dim totResult As Decimal
For Each ct As System.Threading.Tasks.Task(Of Decimal) In CalcTasks
totResult += ct.Result
Next
如果我足够幸运,在我需要结果前,Task总是先完成,即使不走运,也要比按顺序运行每个Task更早得到结果。
凡是遇到一个Task的输出要依赖于另一个Task先完成的情况,你可以在Task之间创建依赖或将Task分组,最简单的办法是使用Wait方法,但它会导致你的应用程序停止执行,直到所有Task全部完成。
Dim tsks() As System.Threading.Tasks.Task = {
Task(Of Decimal).Factory.StartNew(Function() CalcValue(le.Order_Details(0))),
Task(Of Decimal).Factory.StartNew(Function() CalcValue(le.Order_Details(1)))
}
System.Threading.Tasks.Task.WaitAll(tsks)
Task(Of Decimal).Factory.StartNew(Function() CalcValue(le.Order_Details(0))),
Task(Of Decimal).Factory.StartNew(Function() CalcValue(le.Order_Details(1)))
}
System.Threading.Tasks.Task.WaitAll(tsks)
一个更复杂的方法是使用Task对象的ContinueWith方法,当其它Task完成时,它触发一个Task继续运行。下面的例子启动了多个线程,每个都计算订单明细(Order Detail)的值,但都只有等到订单明细上的其它操作完成后才能执行。
For Each ordd As Order_Detail In le.Order_Details
Dim od As Order_Detail = ordd
Dim adjustedDiscount As New Task(Sub() AdjustDiscount(od))
Dim calcedValue As Task(Of Long) =
adjustedDiscount.ContinueWith(Of Long)(Function() CalcValue(od))
adjustedDiscount.Start
Next
Dim od As Order_Detail = ordd
Dim adjustedDiscount As New Task(Sub() AdjustDiscount(od))
Dim calcedValue As Task(Of Long) =
adjustedDiscount.ContinueWith(Of Long)(Function() CalcValue(od))
adjustedDiscount.Start
Next
图 2 并行堆栈窗口提供了一个可视化视图,显示了当前执行的线程的附加信息