In the class below, I have to methods which are doing two totally different things which have nothing to do with eachother. But I am using only one lock object in both of them.
My question is, what is the best practice in such scenarios? Having two separate lock objects for each or sharing one (as we are doing here)?
class MyClass
{
private static object _lock = new object();
public void DoSomething()
{
lock (_lock)
{
}
}
public void DoSomethingTotallyDifferent()
{
lock (_lock)
{
}
}
}
The lock object should be dedicated to the critical resource, not the class.
For example, if your class uses a critical resource A
in the DoSomething
method, then there should be a _lockA
object for it. If DoSomethingTotallyDifferent
accesses also this resource, then it should use the same lock object. If it accesses an other critical resource B
, of course it then should lock that corresponding lock object _lockB
. The methods interfear only, if they have to use the same resource...
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