问题描述
我编写了一些代码来处理事件,如下所示:
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 事件是否已被处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!