Starting a new thread in a foreach loop

This is because you’re closing over a variable in the wrong scope. The solution here is to use a temporary in your foreach loop:

    foreach(MyClass myObj in myList)
    {
        MyClass tmp = myObj; // Make temporary
        Thread myThread = new Thread(() => this.MyMethod(tmp));
        myThread.Start();
    }

For details, I recommend reading Eric Lippert’s post on this exact subject: Closing over the loop variable considered harmful

Leave a Comment