Simple question:
Are "??" and "?." and "? :" thread-safe? And can I trust them? Or I should use other thread-safety solutions?
For instance this code:
public static T Instance => _Instance ?? (_Instance = CreateInstance());
is thread-safe?
It is not threadsafe, due to a race condition. (e.g Thread A checks value, finds it null, thread B checks value, finds it null, thread B initialises value with call to CreateInstance(), thread A intialises value with call to CreateInstance().)
The correct approach to the threadsafe initialisation of a singleton is to use the Lazy<T> class, for example:
public T Instance => _instance.Value;
static Lazy<T> _instance = new Lazy<T>(CreateInstance);
where CreateInstance() returns an instance of type T.
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