Cannot remove .NET event handler
问题:
When my AddIn is loaded it starts listening to the DocumentToBeDestroyed event and it works fine.
However, when later on I try to stop listening to this event I do not succeed and so my handler keeps getting called.
Is there a solution for this?
Here is my code:
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Public Class Commands
Implements IExtensionApplication
Public Sub Initialize() Implements IExtensionApplication.Initialize
AddHandler Application.DocumentManager.DocumentToBeDestroyed, AddressOf docBeginDocClose
End Sub
Public Sub Terminate() Implements IExtensionApplication.Terminate
End Sub
Public Sub docBeginDocClose(ByVal senderObj As Object, _
ByVal docColDocActEvtArgs As DocumentCollectionEventArgs)
System.Diagnostics.Debug.Print("in docBeginDocClose")
End Sub
<CommandMethod("StopEvent")> _
Public Sub StopEvents()
Try
RemoveHandler Application.DocumentManager.DocumentToBeDestroyed, AddressOf docBeginDocClose
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
End Class
解答:
AutoCAD creates an instance of the class that contains the Initialize() function. If the command function is an instance function (not static/shared), then AutoCAD also creates a new instance of the class that contains that function for each document. If the handler is an instance function as well, then you'll get the instance of it that belongs to the same class instance as the command handler.
So you attach one instance’s function to the event inside Initialize() or a command, then you try to remove another instance’s function later on – so you do not remove the function that you attached to the event in the first place.
That’s why your handler keeps being called even after you tried to remove it.
So the solution is to simply make the function static/shared:
Public Shared Sub docBeginDocClose(ByVal senderObj As Object, _
ByVal docColDocActEvtArgs As DocumentCollectionEventArgs)
System.Diagnostics.Debug.Print("in docBeginDocClose")
End Sub
页:
[1]