"is the null coalescing operator (??) in c# thread-safe?" Code Answer

2
public void docallback() {
    (callback ?? new action(() => { }))();
}

is guaranteed to be equivalent to:

public void docallback() {
    action local = callback;
    if (local == null)
       local = new action(() => { });
    local();
}

whether this may cause a nullreferenceexception depends on the memory model. the microsoft .net framework memory model is documented to never introduce additional reads, so the value tested against null is the same value that will be invoked, and your code is safe. however, the ecma-335 cli memory model is less strict and allows the runtime to eliminate the local variable and access the callback field twice (i'm assuming it's a field or a property that accesses a simple field).

you should mark the callback field volatile to ensure the proper memory barrier is used - this makes the code safe even in the weak ecma-335 model.

if it's not performance critical code, just use a lock (reading callback into a local variable inside the lock is sufficient, you don't need to hold the lock while invoking the delegate) - anything else requires detailed knowledge about memory models to know whether it is safe, and the exact details might change in future .net versions (unlike java, microsoft hasn't fully specified the .net memory model).

By Daniel Pinheiro on June 8 2022

Answers related to “is the null coalescing operator (??) in c# thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.