C#模式,以防止事件处理程序挂起两次 [英] C# pattern to prevent an event handler hooked twice

查看:131
本文介绍了C#模式,以防止事件处理程序挂起两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复的:如何确保事件是只订阅一次
已经有一个事件处理程序已添加?

我有一个单例提供一些服务,我的类钩在一些事件上,有时一个类是挂起两次事件,然后被叫两次。
我正在寻找一种古典的方式来防止这种情况发生。不知何故,我需要检查我是否已经挂钩了这个事件...

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;
    }
}

使用上面的代码,如果一个呼叫者订阅了事件多次,它将被忽略。

Using the code above, if a caller subscribes to the event multiple times, it will simply be ignored.

这篇关于C#模式,以防止事件处理程序挂起两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆