Skip to content

Gendarme.Rules.Concurrency.DoNotLockOnThisOrTypesRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

DoNotLockOnThisOrTypesRule

Assembly: Gendarme.Rules.Concurrency
Version: git

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++;
        }
    }
}

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally