What is the preferred way to bubble events?

后端 未结 3 1245
天命终不由人
天命终不由人 2020-12-30 02:25

I have three objects ObjectA has an ObjectB, ObjectB has an ObjectC. When ObjectC fires an event I need ObjectA to know about it, so this is what I\'ve done...



        
3条回答
  •  [愿得一人]
    2020-12-30 03:25

    That's the way I do it. however I would recommend change your firing mechanism to this to make it thread safe

    protected void OnEventFired()
    {
        var tmpEvent = EventFired;
        if(tmpEvent != null)
        {
            tmpEvent();
        }
    }
    

    This keeps it from failing if EventFired becomes null between the null check and the firing.

    Also it is somewhat of a standard to follow the EventHandler pattern for your event delegates.

    protected virtual void OnEventFired(EventArgs e)
    {
        var tmpEvent = EventFired;
        if(tmpEvent != null)
        {
            tmpEvent(this, EventArgs.e);
        }
    }
    

    I was wrong about the threadsafe pattern, here is the full threadsafe event pattern

    /// 
    /// Delegate backing the SomeEvent event.
    /// 
    SomeEventHandler someEvent;
    
    /// 
    /// Lock for SomeEvent delegate access.
    /// 
    readonly object someEventLock = new object();
    
    /// 
    /// Description for the event
    /// 
    public event SomeEventHandler SomeEvent
    {
        add
        {
            lock (someEventLock)
            {
                someEvent += value;
            }
        }
        remove
        {
            lock (someEventLock)
            {
                someEvent -= value;
            }
        }
    }
    
    /// 
    /// Raises the SomeEvent event
    /// 
    protected virtual OnSomeEvent(EventArgs e)
    {
        SomeEventHandler handler;
        lock (someEventLock)
        {
            handler = someEvent;
        }
        if (handler != null)
        {
            handler (this, e);
        }
    }
    

提交回复
热议问题