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
Agree with Reed's answer (+1).
I would add that if you are on .NET 4, you may want to look at the Task Parallel Library to solve this class of problem. Specifically for this case, have a look at Parallel.ForEach().
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
The problem is that you are using the most current value of the object inside of your closure. So, each invocation of the thread is looking at the same value. To get around this, copy the value into a local variable:
foreach(MyClass myObj in myList)
{
MyClass localCopy = myObj;
Thread myThread = new Thread(() => this.MyMethod(localCopy));
myThread.Start();
}
if sequence is not matter than go for
Parallel.ForEach(myList, obj => this.MyMethod(obj) );
Write a Simple Parallel.ForEach Loop
I prefer this way:
public void ThreadingMethod()
{
var myList = new List<MyClass> { new MyClass("test1"), new MyClass("test2") };
Parallel.ForEach(myList, new ParallelOptions() { MaxDegreeOfParallelism = 100 },
(myObj, i, j) =>
{
MyMethod(myObj);
});
}
not tested though....