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 });
          }
       }
    }
  • 相关阅读:
    两个时间相差多少
    JqGrid中文文档
    将A标签的href用iframe打开(JS)
    GridView 自动生成列 没有整理.
    母板页引用JS的办法
    js 判断 文本框是否被全选 ..
    jQuery 调用 Web Services 。。
    WINDOWS 7 + VS2008 +MSSQL 2005 安装成功!
    C# Serializable 的示例
    Microsoft.Crm.WebServices.Crm2007.MultipleOrganizationSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Versi
  • 原文地址:https://www.cnblogs.com/thlzhf/p/2805443.html
Copyright © 2011-2022 走看看