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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With