Difference between manual locking and Synchronized methods

后端 未结 5 743
广开言路
广开言路 2020-12-23 09:08

Is there any difference between this:

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

    public void DoSomething() 
    {
           


        
5条回答
  •  一生所求
    2020-12-23 09:46

    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.

提交回复
热议问题