The code below appears to work – that is, fill an outer List with sub-Lists of incremental integers.
Am I just lucky?
I’m beng careful to pre-allocate “slots” and not cross over.
class Program
{
static List<List<int>> allLists;
static void Main(string[] args)
{
allLists = new List<List<int>>(553);
for (int i = 0; i < 553; i++)
{
allLists.Insert(i, new List<int>());
}
Enumerable.Range(0, 552).AsParallel().ForAll((i) => InsertRange(i));
}
static void InsertRange(int index)
{
allLists[index] = Enumerable.Range(0, 7205).ToList();
}
}
Is there ever a danger that one list will trash another?
Accessing different parts of an array in parallel is thread-safe in .Net. And since
List<T>is backed by an array, I think your code should also be thread-safe.But I think you’re overcomplicating things. You can use PLINQ to generate all the inner lists and then use
ToArray()to create the final array (orToList(), if you really want to createList<T>). Since PLINQ has its own versions ofRange()andToArray()(andToList()), I believe this will be also more efficient.So, I would rewrite your code like this:
Of course, this all makes sense only when parallelizing creating the inner lists will actually speed up your code, but you will have to measure that by yourself.