我如何知道一个.net事件是否已经被处理? [英] How can I know if a .net event is already handled?
问题描述
我已经写了一些代码来处理一个事件,如下所示:
I've written some code to handle an event as follows:
AddHandler myObject.myEvent, AddressOf myFunction
似乎一切都在起作用,但是当我运行调试器时,我发现,通常,<$ c每次 myObject.myEvent
触发时,$ c> myFunction 将运行多次。我发现我已经允许代码添加事件处理程序运行多次,导致这种行为。
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事件是否已经被处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!