I recently ran across this code in one of the projects I’m working on, and I’m not sure how it is supposed to behave.
private static object _syncRoot = 1;
public void DoSomething()
{
lock (_syncRoot)
{
// do stuff...
}
}
I know that it’s customary to use new object() for your lock. How will this lock behave being locked on a boxed integer? What happens if you add another lock with the same value?
private static object _anotherLock = 1;
public void DoSomethingElse()
{
lock (_anotherLock)
{
// do stuff...
}
}
Though not directly related to boxing, this could break if a string like “1” were used instead of an int. Two strings with the same constant value can have the same reference and therefore locking on the ‘separate’ strings would use the same sync block. In general, I would recommend new object() [a known good pattern] over a constant like this.
In fact, I’m not sure if boxing to unique instances is actually in the spec. I could certainly see creating a ‘boxing pool’ for common constants (Like 0 or 1) as a potential CLR improvement. If that were implemented, this usage would fail (in a quite nasty and unpredictable way, most likely.)