Raising C# events with an extension method - is it bad?

后端 未结 6 1260
执念已碎
执念已碎 2020-12-02 10:55

We\'re all familiar with the horror that is C# event declaration. To ensure thread-safety, the standard is to write something like this:

public event EventH         


        
6条回答
  •  生来不讨喜
    2020-12-02 11:43

    Now C# 6 is here, there is a more compact, thread-safe way to fire an event:

    SomethingHappened?.Invoke(this, e);
    

    Invoke() is only called if delegates are registered for the event (i.e. it's not null), thanks to the null-conditional operator, "?".

    The threading problem the "handler" code in the question sets out to solve is sidestepped here because, like in that code, SomethingHappened is only accessed once, so there is no possibility of it being set to null between test and invocation.

    This answer is perhaps tangential to the original question, but very relevent for those looking for a simpler method to raise events.

提交回复
热议问题