Atomicity of C# Coalescing Operator
-
12-11-2019 - |
سؤال
I ran into some singleton code today in our codebase and I wasn't sure if the following was thread-safe:
public static IContentStructure Sentence{
get {
return _sentence ?? (_sentence = new Sentence());
}
}
This statement is equivalent to:
if (_sentence != null) {
return _sentence;
}
else {
return (_sentence = new Sentence());
}
I believe that ?? is just a compiler trick and that the resulting code is still NOT atomic. In other words, two or more threads could find _sentence to be null before setting _sentence to a new Sentence and returning it.
To guarantee atomicity, we'd have to lock that bit of code:
public static IContentStructure Sentence{
get {
lock (_sentence) { return _sentence ?? (_sentence = new Sentence()); }
}
}
Is that all correct?
لا يوجد حل صحيح
لا تنتمي إلى StackOverflow