• CLR Via CSharp读书笔记(11):事件


    事件实现简洁版:

    public event EventHandler<MailEventArgs> NewMail;
    
    protected virtual void OnNewMail(MailEventArgs e) {
        EventHandler<MailEventArgs> temp = Interlocked.CompareExchange(ref NewMail, null, null);
        if (temp != null)
        {
            temp(this, e);
        }
    }
    
    public void SimulateNewMail(String from, String to, String subject)
    {
        MailEventArgs e = new MailEventArgs(from, to, subject);
        OnNewMail(e);
    }

    事件注册:

    多个事件实现:

    public sealed class EventSet {
       // The private dictionary used to maintain EventKey -> Delegate mappings
       private readonly Dictionary<EventKey, Delegate> m_events =
           new Dictionary<EventKey, Delegate>();
    
       // Adds an EventKey -> Delegate mapping if it doesn't exist or 
       // combines a delegate to an existing EventKey
       public void Add(EventKey eventKey, Delegate handler) {
          Monitor.Enter(m_events);
          Delegate d;
          m_events.TryGetValue(eventKey, out d);
          m_events[eventKey] = Delegate.Combine(d, handler);
          Monitor.Exit(m_events);
       }
    
       // Removes a delegate from an EventKey (if it exists) and 
       // removes the EventKey -> Delegate mapping the last delegate is removed
       public void Remove(EventKey eventKey, Delegate handler) {
          Monitor.Enter(m_events);
          // Call TryGetValue to ensure that an exception is not thrown if
          // attempting to remove a delegate from an EventKey not in the set
          Delegate d;
          if (m_events.TryGetValue(eventKey, out d)) {
             d = Delegate.Remove(d, handler);
    
             // If a delegate remains, set the new head else remove the EventKey
             if (d != null) m_events[eventKey] = d;
             else m_events.Remove(eventKey);
          }
          Monitor.Exit(m_events);
       }
    
       // Raises the event for the indicated EventKey
       public void Raise(EventKey eventKey, Object sender, EventArgs e) {
          Delegate d;
          Monitor.Enter(m_events);
          m_events.TryGetValue(eventKey, out d);
          Monitor.Exit(m_events);
    
          if (d != null) {
             d.DynamicInvoke(new Object[] { sender, e });
          }
       }
    }
  • 相关阅读:
    【KVM系列 virt-v2v】virt-v2v过程中的报错
    大机与超级计算机的区别
    多路径 on linux
    ansible 管控 windows
    Linux启动盘
    RHCA 环境命令
    Xshell 4 连接 Ubuntu/Kali 报错 "找不到匹配的key exchange算法"
    security group & ACL
    windows powercfg
    OKD
  • 原文地址:https://www.cnblogs.com/thlzhf/p/2805443.html
Copyright © 2020-2023  润新知