In my program I currently have a structure similar to this:
for (int i=0; i<MyCollection.Count; i++)
{
Task.Factory.StartNew(()=>
{
DoStuffWith(MyCollection[i]);
DoEvenMoreStuffWith(MyCollection[i]);
});
}
It does not work properly because functions DoStuffWith()
and DoEvenMoreStuffWith()
take more time to complete than i++
, hence one of these will usually modify the wrong element of the collection.
I know I can't do int a = i
before the Task.Factory
because it's gonna be the same, really.
How do I make sure each thread works with their own index exclusively?
P.S.: Sorry, I tried looking for an answer here but I don't even know how to google it properly. I know it's something that has to do with reference types and value types, but I've never used them around Task.Factory
before.