Skip to content

Document event implementation reasoning which covers race condition #11877

@ite-jankl

Description

@ite-jankl

The Events section describes how to implement the event ThresholdReached.

The method OnThresholdReached creates a variable and assigns it the event value.

The code makes you think that you could simplify the call from

EventHandler handler = ThresholdReached;
handler?.Invoke(this, e);

to

ThresholdReached?.Invoke(this, e);

However, the docs page How to: Raise Base Class Events in Derived Classes (C# Programming Guide) adds a comment to this statement (albeit it is hidden within quite a lot of code in the example code):

// 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.

I think it would be very helpful to educate users here why the copy is necessary/recommended. I think it should also link to the other page so users can learn why the protected virtual method is used to raise events.

The fact that the assignment operator = makes event copies rather than references was unexpected to me, which would also be a helpful clarification here.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    dotnet/svchelp wantedGood for community contributors to help [up-for-grabs]standard-library/subsvcwon't fixIssues that were closed as part of automated backlog grooming

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions