Difference between manual locking and Synchronized methods

C#.NetMultithreadingLocking

C# Problem Overview


Is there any difference between this:

internal class MyClass
{
    private readonly object _syncRoot = new Object();

    public void DoSomething() 
    {
        lock(_syncRoot)
        {
            ...
        }
    }

    public void DoSomethingElse() 
    {
        lock(_syncRoot)
        {
            ...
        }
    }
}

and this:

internal class MyClass
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    public void DoSomething() 
    {
        ...
    }

    [MethodImpl(MethodImplOptions.Synchronized)]
    public void DoSomethingElse() 
    {
        ...
    }
}

The only difference I see is that the first approach locks on some private member whereas the second approach locks on the instance itself (so it should lock everything else in the instance). Is there any general advice which approach to use? I have currently found two classes with similar purpose in our project each written with different approach.

Edit:

Perhaps one more question. Is this:

internal class MyClass
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    public void DoSomething() 
    {
        ...
    }
}

exactly same like this:

internal class MyClass
{
    public void DoSomething() 
    {
        lock(this) 
        {
            ...
        }
    }
}

C# Solutions


Solution 1 - C#

The first method is preferred because you can (and should) make _syncRoot private. This lowers the risk of deadlocking.

The MethodImplOptions.Synchronized is a left-over from an earlier ambitious idea that turned out to be not so good after all.

Regarding the last question: Yes, according to this blog they are functionally equivalent (but not implemented the same way). And all forms of lock(this) are discouraged, again because of deadlock scenarios.

Solution 2 - C#

check out http://blogs.msdn.com/b/bclteam/archive/2004/01/20/60719.aspx and http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_20926988.html
They discuss about lock(this) too and discourage using it since:

> completely unrelated code can choose to lock on that object as well

Quoting from EE:
> If you lock an object, all other threads that need to access THIS PARTICULAR OBJECT will wait, until the other object finishes. However if you mark a method as Synchronized, THIS PARTICULAR METHOD will not be executed at more than one thread. Lock secures the object, Synchronized secures the method.

Solution 3 - C#

Just having a quick look and found that portable devices do not support MethodImplOptions.Synchronized.

There is also a remark:

> Locking on the instance or on the > type, as with the Synchronized flag, > is not recommended for public types, > because code other than your own can > take locks on public types and > instances. This might cause deadlocks > or other synchronization problems.

source: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=VS.100%29.aspx

Solution 4 - C#

I think the difference would depend on what objects are being referenced in the decorated methods. From what I've read, the decoration actually implements lock() in IL.

The best approach would be to do the most specific locking as necessary.

Solution 5 - C#

This article may help you: http://www.yoda.arachsys.com/csharp/threads/lockchoice.shtml

Generally I would avoid locking on 'this', as private lock variables, provide better control. I would recommend locking on 'this', if it's a custom collection class, something along the lines of SyncRoot, if that is what is required.

Hasanain

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLadislav MrnkaView Question on Stackoverflow
Solution 1 - C#Henk HoltermanView Answer on Stackoverflow
Solution 2 - C#KamyarView Answer on Stackoverflow
Solution 3 - C#Wojtek TurowiczView Answer on Stackoverflow
Solution 4 - C#Steve MalloryView Answer on Stackoverflow
Solution 5 - C#HasanainView Answer on Stackoverflow