I need to read from a list on a (background) thread while it may be updated from another (main thread). So I try to just make a temporary list not to access the original object. As updates may occur on multiple places, it would be convenient to place SyncLock on the read logic. Is that inherently wrong? What are my options for locking this correctly, or other ways to acquire an accessible copy of the list in a multithread condition?
' In Main thread:
Public SomeList = New List(Of SomeClass)
' ..edit list
' In other thread:
Dim tempList As List(Of SomeClass)
SyncLock SomeList
tempList = SomeList.ToList
End SyncLock
SomeList.ToList throws:
ArgumentException, Destination array was not long enough. Check destIndex and length, and the array's lower bounds.
After reviewing
.ToList
and thusNew List(Of SomeClass)(.)
, in Reflector, the exception must be coming fromis2.CopyTo(Me._items, 0)
whereMe._items
has just been set toNew T(count - 1) {}
.This means the number of items in the input collection (cast to
ICollection(Of T)
inis2
) must have increased afteris2.Count
was retrieved.As such, I re-ask the assumption in my now deleted answer: Do all places in the Main thread, in
' ..edit list
, also useSyncLock SomeList
when modifying the list?