Avoid race condition ?. operator
Asked Answered
M

1

2

Does the ?. operator that can be used to invoke a delegate or event avoid race conditions?

Eg. avoid race-condition manually:

//The event-invoking method that derived classes can override.
        protected virtual void OnShapeChanged(ShapeEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<ShapeEventArgs> handler = ShapeChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }

source: msdn

Manny answered 5/5, 2017 at 22:41 Comment(1)
Yes. codeblog.jonskeet.uk/2015/01/30/…Viewless
G
3

Yes

Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code.

...

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only

MSDN Source

Galenical answered 5/5, 2017 at 22:46 Comment(4)
thx btw the example from msdn also works without overriding the virtual method. Do you know why is that?Manny
@GernotAtStackoverflow what virtual method are you referring to?Galenical
protected virtual void OnShapeChanged(ShapeEventArgs e)Manny
sry I got it... forget thatManny

© 2022 - 2024 — McMap. All rights reserved.