Starting a new thread in a foreach loop

后端 未结 5 974
你的背包
你的背包 2020-12-05 10:24

I have a List of objects and I\'d like to loop over that list and start a new thread, passing in the current object.

I\'ve written an example of what I thought shoul

5条回答
  •  醉话见心
    2020-12-05 11:03

    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

提交回复
热议问题