What is the correct way to return a value from a Parallel ForEach or For loop?
For example, is the following code correct / threadsafe?
{ Process[] processes = Process.GetProcesses(); String ProcessName = String.Empty; Parallel.ForEach(processes, curItem => { if (curItem.Handle == this._handle) { ProcessName = curItem.ProcessName; return; } }); return ProcessName; }
OR THAT?
{ Process[] processes = Process.GetProcesses(); List<String> ProcessNames = new List<String>(); Parallel.ForEach(processes, curItem => { ProcessNames.Add(processes.ProcessName); } }); return ProcessNames; }
Finally, what is the behavior of the return keyword inside a Parallel For or ForEach loop?
IE: does it terminate all threads immediately? Could this cause any artifacts you don't expect?
Hope what I ask makes sense.
PS: To be more specific. Looking at the first example, is this my modification of the String stream string and contains the value that I expect due to the return statement? And in the second example, my modification of List List threadsafe? Will all the values ββI expect be added?
Maxim Gershkovich
source share