Correct event invocation.NET Tip of The Day.org

Posted on March 1, 2008 by (author unknown).
Categories: Contributors.

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.


no comments yet.

Leave a comment

Names and email addresses are required (email addresses aren't displayed), url's are optional.

Comments may contain the following xhtml tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>