zoukankan      html  css  js  c++  java
  • 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 });
          }
       }
    }
  • 相关阅读:
    纯真IP数据库格式详解
    iframe框架详解
    搜刮的网址
    Drupal设置首页默认内容
    PHP开发之路之一WAMP的安装和配置
    PHP中json序列化后中文的编码显示问题
    Mysql转化blob为可读
    使用Xtrabackup来备份你的mysql
    MySQL压力测试工具mysqlslap的使用
    Cacti 监控 MySQL
  • 原文地址:https://www.cnblogs.com/thlzhf/p/2805443.html
Copyright © 2011-2022 走看看