Explicit Event add/remove, misunderstood?

后端 未结 3 373
眼角桃花
眼角桃花 2021-01-02 00:57

I\'ve been looking into memory management a lot recently and have been looking at how events are managed, now, I\'m seeing the explicit add/remove syntax for the event subsc

3条回答
  •  时光取名叫无心
    2021-01-02 01:28

    The add/remove properties are basically of the same logic of using set/get properties with other members. It allows you to create some extra logic while registering for an event, and encapsulates the event itself.

    A good example for WHY you'd want to do it, is to stop extra computation when it's not needed (no one is listening to the event).

    For example, lets say the events are triggered by a timer, and we don't want the timer to work if no-one is registered to the event:

    private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    private EventHandler _explicitEvent;
    public event EventHandler ExplicitEvent 
    {
       add 
       { 
           if (_explicitEvent == null) timer.Start();
           _explicitEvent += value; 
       } 
       remove 
       { 
          _explicitEvent -= value; 
          if (_explicitEvent == null) timer.Stop();
       }
    }
    

    You'd probably want to lock the add/remove with an object (an afterthought)...

提交回复
热议问题