0

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 ?

Rajeev
  • 4,571
  • 2
  • 22
  • 35

1 Answers1

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • thanks for your response. but one more question... what is understand from 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 ? – Rajeev Apr 22 '11 at 06:32
  • 1
    @regexhacks: No, the compiler isn't going to start inserting locks for you automatically. You don't want it to - typically you *don't* use objects from multiple threads, so why would you want it to add the cost of locking? I don't really understand your first comment - as I say, you need to lock *everywhere* you access the list. At that point there *won't* be any chance that the list can be accessed simultaneously from multiple threads. – Jon Skeet Apr 22 '11 at 06:41
  • Even I dont understand my first comment :) anyway deleting it. – Rajeev Apr 22 '11 at 06:50