1

There's a modern idiom in C# that utilizes the null-conditional operator to promote thread-safety when using delegates. Namely:

Update?.Invoke(this, theArgs);

Why does this work? Does the C# specification guarantee atomicity in the operation? Does the null-conditional operator make an underlying copy of its operand before executing the Invoke() method?

Zer0
  • 7,191
  • 1
  • 20
  • 34
  • Take a look at https://stackoverflow.com/questions/60678553/why-does-this-common-idiom-for-thread-safe-event-calling-in-c-sharp-works-at-a from a few minutes ago – Flydog57 Mar 14 '20 at 02:21

1 Answers1

1

the Null-conditional operater is roughly equivalent to:

var handler = this.PropertyChanged;
if (handler != null)
{
    handler(…);
}

The part where it creates a local variable? That is what would help with thread safety.

However is is not 100% reliable. See, people have used this pattern before. It has been standing advise for events. But unless you mark handler as volatile, compiler or JiT compiler might cut it out due to being a underused variable. The compiler setting it in itself, might prevent that optimsiation.

But at the end of the day, the only reliable thing is a lock statement.

Christopher
  • 9,634
  • 2
  • 17
  • 31
  • 1
    For delegates, it does indeed guarantee [thread-safety](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#thread-safe-delegate-invocation). – Zer0 Mar 14 '20 at 02:18
  • @Zer0 As I wrote, this pattern has been the go to for decades. But the Compiler Optimisaiton were prone to cut out that local variable. And I am not certain they are reigned in for this case. Without volatile mark, it might be optimized away down the line. – Christopher Mar 14 '20 at 02:21
  • You bring up a good point about `volatile`, but the documentation does state this works. _How_ it works I think is a valid question. C# spec, the compiler, etc.. – Zer0 Mar 14 '20 at 02:23
  • @Zer0: as that will not let me rest, I had to ask it: https://stackoverflow.com/questions/60679273/is-the-null-conditional-operators-thread-safety-save-from-compiler-optimisations – Christopher Mar 14 '20 at 02:41
  • Yeah I wasn't 100% sure myself so I dug around until I fully understood, then [found this](https://stackoverflow.com/a/35786442/3980331) while looking and it goes into great detail about how there still exists a race condition here I normally don't think about. Great read. – Zer0 Mar 14 '20 at 03:34