Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lock on 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 child class instances), to make it thread safe do I have to lock on a static member or does it not matter?

In other words in the example code above is there a difference between InstanceLock() and StaticLock() in terms of thread safety?

like image 310
Dan Avatar asked May 26 '26 16:05

Dan


1 Answers

There is a difference, since the InstanceLock will let two instances of derived classes edit the file at the same time. That is because the lock is not shared between the instances. Prefer the static lock as it will prevent any derived class from entering the lock(_filelockStatic) area from different threads as long as you are in the same app domain

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

// o1._filelock != o2._filelock 
// o1._filelockStatic == o2._filelockStatic 
like image 182
samy Avatar answered May 30 '26 04:05

samy