Variable Copies in Multi-Threading foreach loops question

3 weeks ago 17
ARTICLE AD BOX

I have the following code

List<string> listString = new List<string>(); //Do stuff to populate listString listString = populateList(); foreach(string var in listString) { Task.Run(async () => await ProcessVar(var)); }

In this the code above, I have found that every once in a while 2 threads will utilize the same var values, and I have seen recommendations to do this instead:

List<string> listString = new List<string>(); //Do stuff to populate listString listString = populateList(); foreach(string var in listString) { string varCopy = var; Task.Run(async () => await ProcessVar(varCopy)); }

This solves the problem. But, if I am using a custom class instead of a string, does the same need to happen?

List<CustomClass> listCustom = new List<CustomClass>(); //Do stuff to populate listCustom listCustom = populateList(); foreach(CustomClass var in listCustom) { Task.Run(async () => await ProcessVar(var)); }

That "seems" to work every time without issues that I have seen. But should I actually be doing this:

List<CustomClass> listCustom = new List<CustomClass>(); //Do stuff to populate listCustom listCustom = populateList(); foreach(CustomClass var in listCustom) { CustomClass varCopy = var; Task.Run(async () => await ProcessVar(varCopy)); }

That slows the program down due to the number of instantiations of the custom class which is heavier than string.

Read Entire Article