2

Is there a difference in the below code segments in the way we lock?

public Hashtable mySet= new Hashtable() //mySet is visible to other threads.
lock (mySet) 
   { 
       mySet.Add("Hello World"); 
   } 

and

public Hashtable mySet= new Hashtable();
lock(mySet.SyncRoot)
    { 
       mySet.Add("Hello World"); 
    }
koumides
  • 2,464
  • 5
  • 34
  • 54
  • 2
    Note: everyone assumes that mySet is visible to other threads. You may as well edit your question and add this assumption explicitly. Otherwise there is not much sense in locking local variables. – Alexei Levenkov Jul 03 '12 at 16:59
  • `SyncRoot` is just a leftover of the .net 1.x days. I wouldn't use it. – CodesInChaos Jul 03 '12 at 17:14

3 Answers3

2

As the object passend to the lock will only be used as a "flag holder", this will not make any difference.

Please see this

Community
  • 1
  • 1
GameScripting
  • 16,092
  • 13
  • 59
  • 98
2

lock doesn't actually lock the object in question, so it makes no difference which object is used. Instead it uses the object to establish a protocol and as long as all threads use the same object the protocol guarantees that only one thread will execute code guarded by that lock.

You can think of the object as the microphone on a talk show. Whoever holds the microphone is the only one allowed to talk (I know that is not always how it turns out on some of the shows, but that's the idea anyway).

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
1

According to the MSDN documentation here only a lock on the SyncRoot of a collection does guarantee thread safety.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

marc wellman
  • 5,808
  • 5
  • 32
  • 59