C# pattern to prevent an event handler hooked twice(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# 模式以防止事件处理程序被钩住两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 模式以防止事件处理程序被钩住两次


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01