I have little problem.
My input: configurations - collection that contains for at this moment 2 different objects.
Result looks like was executed two times but with the same parameters. If put break point inside the loop, I see different objects. What I am doing wrong?
List<Thread> threads = new List<Thread>();
foreach (var configuration in configurations)
{
Thread thread = new Thread(() => new DieToolRepo().UpdateDieTool(configuration));
thread.Start();
threads.Add(thread);
}
threads.WaitAll();
Expected result:

What I have:

There's disambiguition with the variable 'configuration'.
Following @HenkHolterman's advice, I'm first posting a cleaner, more precise, solution:
List<Thread> threads = new List<Thread>();
foreach (var configuration in configurations)
{
var threadConfiguration = configuration;
Thread thread = new Thread(() => DieToolRepo().UpdateDieTool(threadConfiguration );
thread.Start();
threads.Add(thread);
}
threads.WaitAll();
Additionally, you can also work it out with for loop:
List<Thread> threads = new List<Thread>();
for (var index=0; index< configurations.Length; index++)
{
Thread thread = new Thread(() => DieToolRepo().UpdateDieTool(configurations[index]));
thread.Start();
threads.Add(thread);
}
threads.WaitAll();
This happens because of the variable 'configuration' is the same for all threads, when this runs. Using this method will create a new copy of Index (localIndex - copied by value), so the shared use of configurations will give different configuration every call.
Though, I'm sure there's a better way to handle those threads, and use safer values accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With