Foreach cycle and tasks

I know from the coding rules that I read you shouldn't do

for (int i = 0; i < 5; i++) { Task.Factory.StartNew(() => Console.WriteLine(i)); } Console.ReadLine(); 

how he writes 5 5, I understand this, and I think I understand why this is happening. I know the solution is just to make

 for (int i = 0; i < 5; i++) { int localI = i; Task.Factory.StartNew(() => Console.WriteLine(localI)); } Console.ReadLine(); 

But is something okay to do something like this?

 foreach (MyClass myClass in myClassList) { Task.Factory.StartNew(() => myClass.DoAction()); } Console.ReadLine(); 

Or do I need to do the same thing as in a for loop.

 foreach (MyClass myClass in myClassList) { MyClass localMyClass = myClass; Task.Factory.StartNew(() => localMyClass.DoAction()); } Console.ReadLine(); 
+6
foreach task
source share
1 answer

This is exactly the same problem with foreach . Following:

 foreach (MyClass myClass in myClassList) { Task.Factory.StartNew(() => myClass.DoAction()); } 

most likely, it will always call the DoAction method for the last element of the list, which can be fixed as follows:

 foreach (MyClass myClass in myClassList) { MyClass localMyClass = myClass; Task.Factory.StartNew(() => localMyClass.DoAction()); } 

But instead of relying on local variables, I would recommend you the following:

 for (int i = 0; i < 5; i++) { Task.Factory.StartNew(localI => Console.WriteLine(localI), i); } 
+6
source share

All Articles