Given,
private object _x;
private object LoadAndSet(ref object x) {
// lock established over read and update
lock (somePrivateObjectNotUsedElsewhereThatIsIrrelvantToTheQuestion) {
if (x == null)
x = Load();
return x;
}
}
Invoked as,
public object Load() {
return LoadAndSet(ref _x);
}
- Are the Read / Writes to the Field (
_x
) "passed by reference" covered under the atomicity/visibility guarantees of thelock
?
That is, is the first code equivalent to the following where the field is used directly? (The assignment occurs directly, instead of via a ref
parameter.)
private object _x;
private object LoadAndSetFieldDirectly() {
// lock established over read and update
lock (somePrivateObjectNotUsedElsewhereThatIsIrrelvantToTheQuestion) {
if (_x == null)
_x = Load();
return _x;
}
}
public object Load() {
return LoadAndSetFieldDirectly();
}
I suspect this to be true due to the use of ldind.ref
and stind.ref
in the method's MSIL; however, the question is begging authoritative documentation/information on the thread-safety (or lack of) when writing such ref
code.