Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `??` thread safe in C#?

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?

like image 613
Mohammad Mirmostafa Avatar asked Apr 06 '26 06:04

Mohammad Mirmostafa


1 Answers

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.

like image 86
Matthew Watson Avatar answered Apr 08 '26 19:04

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!