0

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)
user667118
  • 67
  • 10
  • If the list is read-only then there shouldn't be an issue. The issue would arise if one thread was modifying data in the list while another thread was trying to read it. If there's no modifying then there's no interference with the reading. – jmcilhinney Jun 30 '14 at 00:18
  • Does http://msdn.microsoft.com/en-us/library/3a86s51t.aspx and http://stackoverflow.com/questions/4197238/using-synclock-to-synchronize-access-to-listof-t help? – SomeNickName Jun 30 '14 at 00:18

0 Answers0