0

Feel free to run the code

Thread thread;
for (int i = 6000; i < 6006; i++)
{
    //Thread.Sleep(1);
    thread = new Thread(() => derp(i));

    thread.IsBackground = true;
    thread.Start();
}

private void derp(int a)
{
    MessageBox.Show(a.ToString());
}

It works fine with the thread sleep though, anyone got an explanation?

enter image description here

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Ayy
  • 478
  • 3
  • 11

1 Answers1

1

This is not odd, and its something you will come to learn. The concept is called Capture and Closure

Closure (computer programming)

In programming languages, a closure (also lexical closure or function closure) is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment.1 The environment is a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

The fix to this problem is pretty simple. Instead of capturing the indexer of the "for" loop, we create a local variable which holds a copy of the value.

for (int i = 6000; i < 6006; i++)
{
    var capturedIndex = i;
    thread = new Thread(() => derp(capturedIndex ));

    thread.IsBackground = true;
    thread.Start();
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141