0

Hello people I have a problem using parameters in threads. The problem is that I put an object List<object> as a parameter for a thread array in a foreach loop iterating a list of Lists (List<List<Object>>), and sometimes it duplicates the parameter (i already check that there is not a duplicate object before i put it in a thread). My code is something like this. Does anyone have an idea what is wrong?. Thanks in advance

foreach (List<object> list2 in list1)
{

    threads[i] = new Thread(() =>DoWork(list2, nRetorno));
    threads[i].Name = "thread " + i;
    threads[i].Start();
    Thread.Sleep(5);
    i++;
}
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • This one covers exactly the same issue as yours with almost identical sample code - http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347 . It covers some more details about `foreach` and closures (same as duplicate). – Alexei Levenkov Sep 10 '14 at 22:00
  • Thanks for your answer.. I thought i was making a mistake with Threads.. but this is clearly the main problem.. with more seroious consecuences – hexehell00 Sep 10 '14 at 22:43

2 Answers2

0

In C# there are some weird behaviors working with foreach, try using a reference variable instead the foreach one like:

  foreach (List<object> list2 in list1)
            {
                var list = list2;

                threads[i] = new Thread(() =>DoWork(list, nRetorno));
                threads[i].Name = "thread " + i;
                threads[i].Start();
                Thread.Sleep(5);
                i++;
            }
ferflores
  • 1,084
  • 3
  • 18
  • 35
0

Your lambda is capturing the list2 variable rather than the value. Copy it to a local first:

            foreach (List<object> list2 in list1)
            {
                List<object> list3  = list2;
                threads[i] = new Thread(() =>DoWork(list3, nRetorno));
                threads[i].Name = "thread " + i;
                threads[i].Start();
                Thread.Sleep(5);
                i++;
            }
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87