Raising events vs direct method calls differences

前端 未结 6 2128
夕颜
夕颜 2021-02-04 11:27

Raising an event, will call its event handler. eg http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx

What is the difference between using the events mechan

6条回答
  •  心在旅途
    2021-02-04 12:24

    Raising an event (or Invoking, to use the term from your link) means you are sending the event to all consumers. For example, a window can raise an event when it is clicked with the mouse.

    Consuming an event means that you are receiving and processing the event from whoever sent it. For example, you might want to know when the window is clicked by the mouse.

    If you have only one consumer, then you could accomplish something similar by just supplying a callback directly:

    // 'Event' type:
    delegate void DelMyEvent();
    // consumer:
    class Consumer
    {
        Producer _theProducer;
        void RegisterForNotification()
        {
           _theProducer.OnMyEvent = new DelMyEvent(OnMyEvent);
        }
        void OnMyEvent() { }
    }
    // producer:
    class Producer
    {
       public DelMyEvent OnMyEvent;
       void SendNotification()
       {
          if( OnMyEvent != null ) OnMyEvent();
       }
    }
    

    The event mechanism cleans this up a bit by preventing the consumer from setting the delegate value directly. Instead it makes the consumer register itself with the += operator. When the first consumer registers, the delegate gets set, and when the second consumer registers, their two callbacks get chained together by Delegate.Combine.

提交回复
热议问题