.net - block a value in a box instead of a new object

Recently, I came across this code in one of the projects I'm working on, and I'm not sure how it should behave.

private static object _syncRoot = 1; public void DoSomething() { lock (_syncRoot) { // do stuff... } } 

I know that usually use new object() for your lock. How will this lock be locked for 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... } } 
+4
source share
4 answers

Although this is not directly related to boxing, it can break if you use a string like "1" instead of int. Two lines with the same constant value can have the same link, and therefore locking on "separate" lines will use the same synchronization block. In general, I would recommend a new object () [known good pattern] over a constant like this.

In fact, I'm not sure if boxing is for unique instances in the spec. I could, of course, see the creation of a β€œbox pool” for common constants (like 0 or 1) as a possible improvement to the CLR. If it were to be implemented, this use would fail (in a very unpleasant and unpredictable way, most likely.)

+2
source

lock always uses referential equality.

Two different boxes 1 have two different locks.

+3
source

The second value will be placed in a separate object. Locks will be completely independent of each other because they refer to two different objects.

+1
source

This will not block 1 , it cannot be so short that the boxed objects will be different and these locks will be different.

There is a reason why ValueTypes cannot be locked.

0
source

Source: https://habr.com/ru/post/1382395/


All Articles