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

查看:12
本文介绍了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天全站免登陆