views:

248

answers:

1

I am trying to figure out what this piece of code does. It errors often (not in a system damaging way) but enough that it bothers me. It would be great if I could get some more information on what exactly is going on here and any suggestions on how I might be able to fix/prevent this.

Code

Public Shared Sub Fire(ByVal thisEvent As [Delegate], _
    ByVal ParamArray args() As Object)

    If (thisEvent Is Nothing) Then
        Exit Sub
    End If

    Dim delegates() As [Delegate] = thisEvent.GetInvocationList()

    For Each synch As [Delegate] In delegates
        Try
            synch.DynamicInvoke(args)
        Catch ex As System.Exception
            Util.utEmail.SendErrorMail("Async event fire error.", ex) //Email out error
        End Try
    Next
End Sub

Common Error

User Message: Async event fire error.
Error Type: System.Reflection.TargetInvocationException
Error Message: Exception has been thrown by the target of an invocation.
Error Location: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at TSG.TransIT.UI.UIControls.ctGPViewTrip.updateTrip()
at TSG.TransIT.UI.UIControls.ctGPViewTrip.handleEditTrip(Object sender, EditTripAnnouncementEventArgs e)

+1  A: 

What's going on there is that you are manually invoking a multi-cast delegate. Normally I wouldn't recommend that (it's so much simpler to just invoke the delegate and let it worry about all that), but it looks like you're doing it to improve application logging and error handling. There may or may not be a good reason for that, and so I'll leave the rest of my "just invoke it" speech for another time.

The problem here is that it sounds like this runs on a different thread from some of the invocation targets, and that means by the time this code invokes the delegate with a specific target that target might no longer exist, or an object needed by the invoked code might no longer exist.

Joel Coehoorn