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++; } 
2
  • This one covers exactly the same issue as yours with almost identical sample code - stackoverflow.com/questions/8898925/… . It covers some more details about foreach and closures (same as duplicate). Commented Sep 10, 2014 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 Commented Sep 10, 2014 at 22:43

2 Answers 2

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++; } 
Sign up to request clarification or add additional context in comments.

Comments

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++; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.