How can I know if a .net event is already handled?(我如何知道 .net 事件是否已被处理?)
问题描述
我编写了一些代码来处理事件,如下所示:
I've written some code to handle an event as follows:
AddHandler myObject.myEvent, AddressOf myFunction
一开始似乎一切正常,但是当我运行调试器时,我发现 myFunction 经常会在每次 myObject.myEvent 触发时运行几次.我发现我允许代码添加事件处理程序多次运行,导致了这种行为.
It seemed that everything was working at first, but when I ran the debugger, I discovered that oftentimes, myFunction would run several times each time myObject.myEvent fired. I figured out that I had allowed the code to add the event handler to run more than once, resulting in this behavior.
有没有办法让我做这样的事情?
Is there a way I can do something like this?
If myObject.myEvent is not handled Then
AddHandler myObject.myEvent, AddressOf myFunction
End If
推荐答案
假设发布事件的不是你的代码,你不能.这个想法是订阅者彼此隔离 - 您无法了解其他事件订阅者,自己引发事件等.
Assuming it's not your code that's publishing the event, you can't. The idea is that subscribers are isolated from each other - you can't find out about other event subscribers, raise the event yourself etc.
如果问题是您多次添加自己的处理程序,您应该能够通过跟踪您是否添加了处理程序来自己解决这个问题.Steven 在添加之前删除处理程序的想法是一个有趣的解决方法:尝试删除处理程序是有效的,即使它没有被订阅.但是,我认为这是您的应用程序不知道它应该做什么的解决方法.这是一个非常快速的短期解决方案,但我会担心将其长期保留.
If the problem is that you're adding your own handler multiple times, you should be able to fix that yourself by keeping track of whether you have added a handler. Steven's idea of removing the handler before adding it is an interesting workaround: it's valid to attempt to remove a handler even when it isn't subscribed. However, I'd regard this as a workaround to your app not really knowing what it should be doing. It's a very quick short-term fix, but I'd be worried about leaving it in for the longer term.
这篇关于我如何知道 .net 事件是否已被处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何知道 .net 事件是否已被处理?
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
