Skip to content

Gendarme.Rules.Concurrency.DoNotLockOnThisOrTypesRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

DoNotLockOnThisOrTypesRule

Assembly: Gendarme.Rules.Concurrency
Version: 2.10

Description

This rule checks if you're using lock on the current instance (this ) or on a Type. This can cause problems because anyone can acquire a lock on the instance or type. And if another thread does acquire a lock then deadlocks become a very real possibility. The preferred way to handle this is to create a private System.Object instance field and lock that. This greatly reduces the scope of the code which may acquire the lock which makes it much easier to ensure that the locking is done correctly.

Examples

Bad example (this):

public void MethodLockingOnThis ()
{
    lock (this) {
        producer++;
    }
}

Bad example (type):

public void MethodLockingOnType ()
{
    lock (this.GetType ()) {
        producer++;
    }
}

Good example:

class ClassWithALocker {
    object locker = new object ();
    int producer = 0;
    public void MethodLockingLocker ()
    {
        lock (locker) {
            producer++;
        }
    }
}
Clone this wiki locally