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# 模式以防止事件处理程序被钩住两次
基础教程推荐
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
