vb.net - Events with a handled property. Is this way save?
Ok, I have a winforms app and my code works fine. But I want to know if my code is bullet proof or if it only works without load.
Let me explain it:
I have a windows form where I have overridden the OnKeyDown method:
Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
dim args as new ActionEventArgs(ActionType.Bark)
RaiseEvent Action(me, args)
e.Handled = args.Handled
MyBase.OnKeyDown(e)
End Sub
As you can see I raise an custom event and query the Handled Variable of it afterwards. My Event / ActionEventArgs looks like this:
Public Event Action(sender as Object, e as ActionEventArgs)
Public Class ActionEventArgs
Inherits EventArgs
Public Handled as Boolean
Public Action as Action
Public Sub New(ByVal action as ActionType)
Me.Action = action
End Sub
End Class
where Acti开发者_运维知识库onType is this Enum
Public Enum ActionType
Bark,
Jump,
FireNukeWithoutFurtherWarning
End Enum
Now I have a class that is registered to this event and, if it knows how to handle the ActionType it sets Handled to true.
Public Sub actionHandler(ByVal sender as Object, e as ActionEventArgs) Handles me.Action
If e.Handled then return
If e.Action = ActionType.Bark
Bark()
e.Handled = true
End If
End If
I tried this code at my developer machine and it seems to work. In the OnKeyDown Method, everytime I query the Handled variable, my actionHandler method did run first.
But I asking me if this is only the case because my developer machine is in idle state and the event queue is processed so fast or can I expect the RaiseEvent(...)
method to wait until every registered EventHandler has finished it's taks?
Raising an event is exactly the same as calling a method (specifically, it's calling a MulticastDelegate
, which is a list of pointers to other methods, each of which will be executed); the code will process all of the event handlers before it continues to your next statement.
RaiseEvent waits for each event to finish (or at least has to) because 'normal' events are not fired asynchronously. RaiseEvent does nothing more than go through a list of Handlers and invoking each.
精彩评论