C#模式prevent事件处理程序两次挂钩 [英] C# pattern to prevent an event handler hooked twice
问题描述
的复制:<一href=\"http://stackoverflow.com/questions/367523/how-to-ensure-an-event-is-only-subscribed-to-once\">How确保一次的事件只认购
和已添加的事件处理程序?
Duplicate of: How to ensure an event is only subscribed to once and Has an event handler already been added?
我有一个单身的提供了一些服务,我的课挂接到它的一些事件,有时一类是挂钩两次的事件,然后被调用两次。
我正在寻找的发生古典的方式来prevent这一点。不知何故,我需要检查,如果我已经迷上这个事件......
I have a singleton that provides some service and my classes hook into some events on it, sometimes a class is hooking twice to the event and then gets called twice. I'm looking for a classical way to prevent this from happening. somehow I need to check if I've already hooked to this event...
推荐答案
明确落实该事件,并检查调用列表。您还需要检查null:
Explicitly implement the event and check the invocation list. You'll also need to check for null:
using System.Linq; // Required for the .Contains call below:
...
private EventHandler foo;
public event EventHandler Foo
{
add
{
if (foo == null || !foo.GetInvocationList().Contains(value))
{
foo += value;
}
}
remove
{
foo -= value;
}
}
使用上面的code,如果呼叫者订阅事件多次,它将简单地被忽略。
Using the code above, if a caller subscribes to the event multiple times, it will simply be ignored.
这篇关于C#模式prevent事件处理程序两次挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!