Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour of loop

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: enter image description here

What I have:

enter image description here

like image 512
Mroczny Arturek Avatar asked Aug 11 '26 09:08

Mroczny Arturek


1 Answers

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.

like image 84
Ori Nachum Avatar answered Aug 13 '26 00:08

Ori Nachum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!