Locking a static or instance variable in an abstract class

public abstract BaseClass
{
    private static readonly object _filelockStatic = new object();
    private readonly object _filelock = new object();

    public void StaticLock()
    {
        lock(_filelockStatic)
        {
             //Edit a common text file (common to all children)
        }
    }

    public void InstanceLock()
    {
        lock(_filelock)
        {
             //Edit a common text file (common to all children)
        }
    }
}

      

If I have an abstract class with a method that edits a text file (one text file common to all instances of child classes) to make it thread safe, do I need to lock the static member, or does it not matter?

In other words, in the above code example, is there a difference between InstanceLock()

and StaticLock()

in terms of thread safety?

+3


source to share


1 answer


There is a difference because it InstanceLock

allows two instances of derived classes to edit a file at the same time. This is because locking is not used between instances. Prefer a static lock as it will prevent any derived class lock(_filelockStatic)

from being injected into the scope from different threads if you are in the same application domain



var o1 = new DerivedClass();
var o2 = new DerivedClass();

// o1._filelock != o2._filelock 
// o1._filelockStatic == o2._filelockStatic 

      

+3


source







All Articles