Skip to content

Gendarme.Rules.Concurrency.DoNotUseMethodImplOptionsSynchronizedRule(git)

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

DoNotUseMethodImplOptionsSynchronizedRule

Assembly: Gendarme.Rules.Concurrency
Version: git

Description

This rule fires if a method is decorated with MethodImpl(MethodImplOptions.Synchronized). The runtime synchronizes those methods automatically using a lock(this) for instance methods or a lock(typeof(X)) for static methods. 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:

[MethodImpl (MethodImplOptions.Synchronized)]
public void SychronizedMethod ()
{
    producer++;
}

Good example:

public 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