使用Anonymous方法创建线程 - 如何解决Closure的问题?

时间:2014-07-24 21:05:41

标签: .net vb.net

假设您有以下内容:

For i as Integer = 0 To 10
   For j as Integer = 0 to 10
      Dim t as New Thread (
          Sub()
            Console.WriteLine("Hello: " & i & j)
          End Sub 
   )
      t.Start()
   Next
Next

我知道这是一个封闭问题,但是为这种情况编写匿名方法的正确方法是什么...我希望打印所有数字从1到10为"我"和" j"。

的所有数字从1到10

1 个答案:

答案 0 :(得分:3)

您只需要在循环中获取ij 的本地副本:

For i as Integer = 0 To 10
   For j as Integer = 0 to 10
      Dim iCopy = i
      Dim jCopy = j
      Dim t as New Thread (
          Sub()
            Console.WriteLine("Hello: " & iCopy & jCopy)
          End Sub 
      )
      t.Start()
   Next
Next

然后,您将在循环的每次迭代中获得新的iCopyjCopy变量。

此建议只是遵循您应该收到的原始代码警告的具体结果:

warning BC42324: Using the iteration variable in a lambda expression may have 
unexpected results.  Instead, create a local variable within the loop and assign
it the value of the iteration variable.