Mori
Mori

Reputation: 2574

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

    }
}
}

Upvotes: 4

Views: 1007

Answers (2)

Dieter Meemken
Dieter Meemken

Reputation: 1967

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

Upvotes: 6

Patrick Hofman
Patrick Hofman

Reputation: 156968

The question is: can DoSomething or DoSomethingTotallyDifferent be called from each other? If so, you can create a deadlock. Maybe it doesn't call each other now, but they might in the future.

My two cents: better be safe than sorry. Use two separate lock variables.

Upvotes: 4

Related Questions