.NET Tip of The Day
Learn one new .NET trick every day
Web GTD system from the creators of DotNetTipOfTheDay.org          Login or Join

Correct event invocation

Be aware that if there are no subscribers a .NET event will be null. Therefore when raising the event from C# test it for null first.

    public event EventHandler SelectedNodeChanged;

 

    protected virtual void OnSelectedNodeChanged(object sender, EventArgs e)

    {

        //Event will be null if there are no subscribers

        if (SelectedNodeChanged != null)

        {

            SelectedNodeChanged(this, e);

        }

    }

However in multithreaded application the last subscriber can unsubscribe immediately after the null check and before the event is raised. To avoid a null reference exception make a temporary copy of the event.

    public event EventHandler SelectedNodeChanged;

 

    protected virtual void OnSelectedNodeChanged(object sender, EventArgs 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 handler = SelectedNodeChanged;

 

        //Event will be null if there are no subscribers

        if (handler != null)

        {

            handler(this, e);

        }

    }

submitted by Sergey P.

3/1/2008
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.