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();
Scott Chamberlain
source share