I have a List of objects shared by multiple threads, it sometimes generate IndexOutOfRangeException when trying to Clear
. While searching for solution I found that I should use SyncLock while accessing the List.
But my question if what is the importance of lockObject
in SyncLock
block
e.g. while clearing myList
can I use
Synclock myList
myList.Clear
End SyncLock
or lockObject should be different from myList?
Edit:
What I think about sysnclock is "lock is obtained for object specified as lockObject". What if I specify list to be cleared as lockObject, shouldn't the compiler supposed to obtain the exclusive access to list before clearing it ?
The choice is arbitrary - the reference can be completely independent from the data you're accessing within the block, or you can use something like a list reference.
Personally I like to keep a separate object solely for the purpose of locking - if it's a private readonly variable, you know that no code outside the class will be locking on the same monitor. Of course, if you have lots of different code accessing the same shared data, you may need to expose the lock more widely - but it's generally preferable to encapsulate all the actions which need to acquire the lock in one class, and then keep the lock itself private.
Note that you shouldn't just use the lock for clearing - you'll need to use it everywhere that you access the list.