Correct event invocation.NET Tip of The Day.org
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.
Simplify Your Cleaning [How To]Lifehacker »« Use Unix Commands in Windows’ Built-In Command Prompt [Command Line]Lifehacker
