2014-10-08 78 views
1

我有一个事件,我注册事件处理程序。如何避免多次注册事件

event Action OnGameList; 

然后例如我到达像这样的代码:

backend.OnGameList += ProcessGameList; 
backend.GetGameList(); //this will trigger the above event. 
每个i达到这个代码时间

,该处理程序中的溶液。这意味着第二次将被调用两次。当然 我可以在这样的功能将其删除:

backend.OnGameList -= ProcessGameList; 

,但我有一种感觉,有这类问题更好的解决方案。

+1

没有更多的代码很难说。显而易见的答案是只在代码中添加事件一次,而不是重复调用,但很难给出更具体的建议,而不理解为什么您已经多次添加它。 – Chris 2014-10-08 12:51:39

+0

您可以先安全地移除,然后重新添加。否则,你将不得不检查它是否已经注册。 – 2014-10-08 12:58:58

+1

我必须承认,如果我的设计只被我使用,并且我只想附加处理程序一次,即使附加例程被调用了n次(可以说每次自定义弹出窗口都会出现),我总是使用 - =之前+ =。它从未坠毁,并始终帮助。 IIRC。 – icbytes 2014-10-08 13:03:35

回答

3

我认为你应该使用某种支持字段来跟踪你已经订阅。即

private bool _subscribed = false; 

    SubscribeToOnGameListEvent(); 
    backend.GetGameList(); 

    private void SubscribeToOnGameListEvent() 
    { 
     if (!_subscribed) 
     { 
      backend.OnGameList += ProcessGameList; 
      _subscribed = true; 
     } 
    } 
3

您可以检查特别代表的存在调用列表:

class Foo 
{ 
    private EventHandler bar; 

    public event EventHandler Bar 
    { 
     add 
     { 
      if (bar == null) 
      { 
       bar = value; 
      } 
      else 
      { 
       if (!bar.GetInvocationList().Contains(value)) 
       { 
        bar += value; 
       } 
      } 
     } 
     remove 
     { 
      // ... 
     } 
    } 

    public void RaiseBar() 
    { 
     if (bar != null) 
     { 
      bar(this, EventArgs.Empty); 
     } 
    } 
} 
+0

这似乎是一个很好的解决方案,但是在我的具体情况下,我无法真正使用它,因为我的事件是从WCF服务参考中自动生成的类。 – clamp 2014-10-09 12:41:40