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# 模式以防止事件处理程序被钩住两次


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01