Let's suppose I have a thread that locks on an object reference
Thread #1
lock(myObj) { ... }
later in code I have myObj = new XYZObj();
and then Thread #2 locks on it
lock(myObj) { ... }
Will this code be thread safe, if the object reference has changed? When the object reference changes, the first lock is still valid?
Locks work on instances, not variables.
The lock
statement will hold its own reference to the instance so that it will only exit the instance you entered.
The spec says:
where x is an expression of a reference-type, is precisely equivalent to
System.Threading.Monitor.Enter(x); try { ... } finally { System.Threading.Monitor.Exit(x); }
except that x is only evaluated once.
If you re-assign the variable between the two locks, you will get two valid locks on two different instances.
In general, however, you should never do that; it's a recipe for subtle bugs and race conditions.
You should only lock on dedicated readonly lock objects.
No. They will both be locking on different objects.
According to MSDN
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With