Creating a thread using an Anonymous method how to solve issue with Closure?

Suppose you have the following:

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

I know this is a closure problem but what is the right way to write the anonymous method for this case... I would like it to print all the numbers from 1 - 10 for "i" and all the numbers from 1 - 10 for "j".

Jon Skeet
people
quotationmark

You just need to take a local copy of i and j within the loop:

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

Then you'll get a new iCopy and jCopy variable on each iteration of the loop.

This advice is just the concrete result of following the warning you should have received with your original code:

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.

people

See more on this question at Stackoverflow