Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lock() inside instance constructor

I found in some code lock statement inside instance constructor. The code looks like this

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

    public MyClass(string parameter)
    {
        lock (_syncRoot)
        {
            // some code
        }
    }
}

I think lock is useless here because this code cannot be called in different threads. Every thread will create its own object instance calling constructor. But maybe I'm wrong and don't know something. Thanks.

Edit: In the first answer of this question C# Am i using lock correctly I found

It's best to put a lock around the code within the constructor, as I believe it's possible in certain circumstances that methods can be called before the constructor block has finished executing.

So, it could be an answer.

like image 207
Vasyl Zv Avatar asked Feb 09 '17 10:02

Vasyl Zv


1 Answers

You are absolutely right, lock is completely useless, because it is locking on an instance variable, while no outside caller could access it anyway.

I would imagine that this code would become useful if _syncRoot were declared static, in which case the semantic of critical section protected by the lock would change from one-per-instance to one-per-class.

Edit: (in response to a comment by Sinatr) The above makes an assumption about the code inside the critical section, that it makes no method calls that use _syncRoot object for locking as well. If there are such methods calls, their critical sections would be granted access, because the thread already holds the monitor.

like image 70
Sergey Kalinichenko Avatar answered Oct 11 '22 11:10

Sergey Kalinichenko