The lock(this)
will lock on the entire instance while lock(privateObject)
will only lock that specific instance variable. The second one is the better choice since locking on the entire instance will prevent other threads from being able to do anything with the object.
From MSDN:
In general, avoid locking on a public
type, or instances beyond your code's
control. The common constructs lock
(this), lock (typeof (MyType)), and
lock ("myLock") violate this
guideline:
lock (this) is a problem if the
instance can be accessed publicly.
lock (typeof (MyType)) is a problem if
MyType is publicly accessible.
lock(“myLock”) is a problem since any
other code in the process using the
same string, will share the same lock.
Best practice is to define a private
object to lock on, or a private static
object variable to protect data common
to all instances.
In this particular case, the collection is static which effectively means there is a single instance but that still doesn't change how the lock(this)
and lock(privateObject)
would behave.
By using lock(this)
even in a static collection you are still locking the entire instance. In this case, as soon as thread A acquires a lock for method Foo()
all other threads will have to wait to perform any operation on the collection.
Using lock(privateObject)
means that as soon as thread A acquires a lock for method Foo()
all other threads can perform any other operation except Foo()
without waiting. Only when another thread tries to perform method Foo()
will it have to wait until thread A has completed its Foo()
operation and released the lock.