12
Consider the following code sample, which creates an enumerable collection of integers and processes it in parallel:
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
Parallel.ForEach(CreateItems(100), item => ProcessItem(item));
}
private static IEnumerable<int> CreateItems(int count)
{
for (int i = 0; i < count; i++)
{
yield return i;
}
}
private static void ProcessItem(int item)
{
// Do something
}
}
Is it guaranteed that the worker threads generated by Parallel.ForEach() each get a different item or is some locking mechanism around incrementation and returning of i required?