I would like to iterate through a list inside of a Parallel.ForEach loop, but the list will be a shared resource that I have to take turns accessing, which I think would defeat the purpose of the parallelism. Access to the list is read-only, so I was wondering if there was a way to make copies of the list, and allow each thread to pick one if it is not in use by one of the other threads.
Dim collCopy1 As List(Of InnerType) = innerCollection.ToList()
Dim collCopy2 As List(Of InnerType) = innerCollection.ToList()
Dim collCopy3 As List(Of InnerType) = innerCollection.ToList()
Dim collCopy4 As List(Of InnerType) = innerCollection.ToList()
Dim Lock As New Object
Dim ParallelOpts As New ParallelOptions()
ParallelOpts.MaxDegreeOfParallelism = 4
Task.Factory.StartNew(Sub()
Parallel.ForEach(outerCollection,
ParallelOpts,
Sub(outerItem As OuterType)
'Pick from collCopy1, collCopy2, collCopy3, collCopy4 here, assign to innerList, and SyncLock it
For Each innerItem As InnerType In innerList
'Do some stuff
Next
End Sub)
End Sub)