Thread parameters being changed

You should be careful about accidentally modifying captured variables like i after starting the thread, because the i is shared. The i variable refers to the same memory location throughout the loop’s lifetime. The solution is to use a temporary variable like this:

for (int i = 0; i < _threadCount; i++)
{
      var i1 = i;
      Thread thread = new Thread(() => WorkerThread(i1));
      thread.Start();
      _threads.Add(thread);
}

Read more about Closures here : The Beauty of Closures from (Jon Skeet) and Lambda expressions and captured variables from (Joseph Albahari).

Leave a Comment