In a class I'm maintaining I have 2 methods using a common lock on part of their codes:
class A
{
private readonly object o = new object();
public void F1(B b)
{
...
lock (o)
{
...
b.Data.Add(...);
...
}
...
}
public void F2(B b)
{
...
lock (o)
{
...
b.Data.Add(...);
...
}
...
}
}
So the locked sections cannot be run concurrently even if working on different B
entities.
They do not write any external state (nor read any by the way) and only change the state of their parameters.
In order to protect access to parameters I would do this instead:
lock(b)
{
...
}
Note that each Data
is unique to each B
instance and only edited there.
And other properties of b
can be edited inside the locked section so b
seems the right level to lock to group all these changes to guarantee atomicity.
- Can I safely remove the global lock on
o
and instead use the more granular one onb
? - If no, what could be the pitfalls?