每个任务[Vb.Net]

时间:2017-11-29 09:49:16

标签: vb.net

我遇到__LINE__的问题,我不明白为什么它不起作用。

System.Threading.Tasks

我总是得到这个结果

Dim table_sec As New Dictionary(Of String, List(Of Double))

table_sec.Add("SEC01", New List(Of Double)(New Double() {10.00, 5.00}))
table_sec.Add("SEC02", New List(Of Double)(New Double() {9.00, 8.00}))
table_sec.Add("SEC03", New List(Of Double)(New Double() {5.00, 2.00}))

    Dim pair As KeyValuePair(Of String, List(Of Double))
    Dim tasks As New List(Of Task)()

    For Each pair In table_sec
    Dim t As Task = Task.Run(Sub()
    Console.WriteLine("Key = " & pair.Key)
                   End Sub)

    tasks.Add(t)

    Next     

   Task.WaitAll(tasks.ToArray())

你能告诉我出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

我多年没有使用过VB.Net而且我无法测试它,但您可以尝试按照我建议的link的简单示例使用捕获的引用的本地副本:

Dim table_sec As New Dictionary(Of String, List(Of Double))

table_sec.Add("SEC01", New List(Of Double)(New Double() {10.00, 5.00}))
table_sec.Add("SEC02", New List(Of Double)(New Double() {9.00, 8.00}))
table_sec.Add("SEC03", New List(Of Double)(New Double() {5.00, 2.00}))

Dim pair As KeyValuePair(Of String, List(Of Double))
Dim tasks As New List(Of Task)()

For Each pair In table_sec
  Dim p As KeyValuePair(Of String, List(Of Double))
  p = pair ' make a copy to the actual pair in this loop iteration
  Dim t As Task = Task.Run(Sub()
  Console.WriteLine("Key = " & p.Key) ' capture local copy p instead of pair
               End Sub)

  tasks.Add(t)

Next     

Task.WaitAll(tasks.ToArray())