Difference between manual locking and Synchronized methods

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

Is there any difference between this:

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

    public void DoSomething() 
    {
           


        
5条回答
  •  旧时难觅i
    2020-12-23 09:52

    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.

提交回复
热议问题