AnsweredAssumed Answered

Please Help- Intermitent AddHandler Bug?

Question asked by Edwin Thompson on Aug 1, 2016
Latest reply on Aug 2, 2016 by Jesse Seger

This project works nicely which allows various information to be retrieved from a SW document.  The goal is to automatically re-establish events when the document is changed.  The original approach would sometime generate two identical events which would run simultaneously and crated problems.  This was a significant issue so the approach below is to always Remove the handler before attempting to create a new one with the new document.  Therefore, even if AttachSWEvents is called more than once, there would only ever be one event started for the current document.  This works very nicely, except after a randomly a document will not "register" properly. 


Surprisingly, if the current document is changed to a different document and then refocused on, many times the Event can be re-established.


In addition to the typical overhead for events (swApp, swModel, etc.) there is the AttachSWEvents sub:


Sub AttachSWEvents()

            Try  'To prevent multiple events from being registered, always remove the current event

                RemoveHandler msrcPartDoc.UserSelectionPostNotify, AddressOf msrcPartDoc_NewSelectionNotify

                RemoveHandler msrcPartDoc.destroynotify2, AddressOf msrcPartDoc_DestroyNotify

                Debug.Print("*****" + swModel.GetPathName + " Part Removed")

            Catch ex As Exception

                Debug.Print("***failed to Remove Part Event Handler")

            End Try

            Try  'Add the new event for the loaded document

               AddHandler msrcPartDoc.UserSelectionPostNotify, AddressOf msrcPartDoc_NewSelectionNotify

                Debug.Print("*****" + swModel.GetPathName + " Part Added")

             Catch ex As Exception

                Debug.Print("***** failed to Register Part Handler")

            End Try

            Try  'Add the new destroy event for the loaded document

                AddHandler msrcPartDoc.destroynotify2, AddressOf msrcPartDoc_DestroyNotify

            Catch ex As Exception

                Debug.Print("**** failed to Register Destroy Part Handler")

            End Try

End Sub


Private Function swApp_ActiveDocChangeNotify() As Long

         msrcPartDoc = Nothing 'The main program detects when = nothing, re-established the current document and activates the AttachSWEvents() Sub

         swModel = Nothing

End Function


This all works fine. However, sometimes after as few as three document change and as many as 16 document changes, the new Events will create and error.


Part of the VS Result window is shown below:

The Line shown in Red Above is the code that fails (once in awhile).  Any idea why this happens so randomly?  Any ideas how to correct this?