Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for having more than a lock object in a class

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)
    {

    }
}
}
like image 785
Mori Avatar asked Jan 07 '23 00:01

Mori


1 Answers

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...

like image 74
Dieter Meemken Avatar answered Jan 20 '23 11:01

Dieter Meemken