Question about custom events

I am doing custom events for C # and sometimes it does not work.

This is how I make the event:

    private bool isDoorOpen;
    public bool IsDoorOpen {
        get { return isDoorOpen;}
        private set { isDoorOpen = value; DoorsChangeState(this, null);}
    }

And these are event announcements:

    //events        
    public delegate void ChangedEventHandler(Elevator sender, EventArgs e);
    public event ChangedEventHandler PositionChanged;
    public event ChangedEventHandler DirectionChanged;
    public event ChangedEventHandler BreaksChangeState;
    public event ChangedEventHandler DoorsChangeState;

This works as long as there are event-related methods, but if that doesn't happen, it throws a null ref exception. What am I doing wrong?

+5
source share
5 answers

Recommended event trigger method:

var handler = this.DoorsChangeState;
if (handler != null)
    handler(this, null);

The reason for copying the local handler is that the event handler changes to another thread while you check for null.

EDIT: Found an article on race status. http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx

+10
source

, ( ) , SO.

, :

public static class EventHandlerExtensions
{
    public static void FireEvent<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs
    {
        var temp = handler;
        if (temp != null)
        {
            temp(sender, args);
        }
    }

    public static void FireEvent(this EventHandler handler, object sender)
    {
        var temp = handler;
        if (temp != null)
        {
            temp(sender, EventArgs.Empty);
        }
    }
}

, :

public bool IsDoorOpen
{
    get { return isDoorOpen;}
    private set
    {
        isDoorOpen = value;
        DoorsChangeState.FireEvent(this);
    }
}
+4

, NullReferenceException. , , .

:

if(DoorsChangeState != null)
{
   DoorsChangeState(this, null); // Only fire if subscribed to
}
0

, :

if (DoorsChangeState != null)   
  DoorsChangeState(this, null);

DoorsChangeState null, , .

0

, .

.

var temp = EventName;
if(EventName!= null)
   temp(this, null);
0

All Articles