Is there a way to know in VB.NET if a handler has been registered for an event?

前端 未结 6 1239
难免孤独
难免孤独 2021-01-17 14:07

In C# I can test for this...

public event EventHandler Trigger;
protected void OnTrigger(EventArgs e)
{
    if (Trigger != null)
        Trigger(this, e);
}
         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 14:41

    First of all, there's a problem with your c# code. It should read like this to reduce the likelihood of a race condition on removing the last handler in a separate thread at just the wrong time (hint on why it works: mulit-cast delegates are immutable):

    public event EventHandler Trigger;
    protected void OnTrigger(EventArgs e)
    {
        var temp = Trigger;
        if (temp != null)
            temp(this, e);
    }
    

    Secondly, there's no need for this code at all in VB.Net. VB handles events a little differently, such that you should not check at all whether any handlers are registered. It's safe and preferred to just raise the event:

    Public Event Trigger As EventHandler
    Friend Sub OnTrigger(ByVal e As EventArgs)
        RaiseEvent Trigger(Me, e)
    End Sub
    

提交回复
热议问题