在使用自定义委托时检查事件处理程序是否有任何订阅者

时间:2015-05-08 08:15:37

标签: c# events delegates

所以这个想法很简单,我如何检查是否有任何重复的订阅者。

基本上如果我有

  

_moduleEvent + = _coachesEvents.OnDifficultyScoreListChanged;

订阅多个 位置,我不希望调用两次(或更多)的方法。

我的当前代码(研究后添加了逻辑):

        /// <summary>
        /// Delegate that points to the multiple module methods
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private delegate void ModuleEventHandler(object sender, OpportunityEventArgs args);

        /// <summary>
        /// 
        /// </summary>
        private event ModuleEventHandler _moduleEvent
        {
            add
            {
                if (_moduleEvent == null || !_moduleEvent.GetInvocationList().Contains(value))
                {
                    _moduleEvent += value;
                }
            }
            remove
            {
                _moduleEvent -= value;
            }
        }

如果我检查它是否为null并检查GetInnvocationList,我会收到一个错误,即_moduleEvent应出现在+ = etc的左侧。

        /// <summary>
        /// Check whether there are any subscribers
        /// </summary>
        private void _onModuleEvent(BusinessEntities.Opportunity o)
        {
            if (_moduleEvent != null)
                _moduleEvent(this, new OpportunityEventArgs() { Opportunity = o });
        }

我也看到_moduleEvent应出现在上面+ = error的左侧。

我只能假设它与自定义代理有关吗?如果我在eventHandler中删除了添加/删除,显然一切正常。

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:0)

我建议您创建字典并检查

按以下方式创建课程

public class Subscription
{
  public readonly MethodInfo MethodInfo;
  public readonly WeakReference TargetObjet;

  public Subscription(Action<Tmessage> action, EventAggregator eventAggregator)
  {
      MethodInfo = action.Method;
      TargetObjet = new WeakReference(action.Target);
  }
}

在暴露事件

的类中使用此类
Public class EventExposer
{
  private Dictionary<Type, IList> subscriber;

  public EventExposer()
  {
            subscriber = new Dictionary<Type, IList>();
  }

   public void AddEvent(Action action)
   {
            Type t = typeof(action.Target);
            if (!subscriber.ContainsKey(t))
            {
                    subscriber.Add(t, action);
            }
   }

}