设为首页收藏本站

晓东CAD家园-论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 175|回复: 0

不能移除.NET事件句柄

[复制链接]

已领礼包: 40个

财富等级: 招财进宝

发表于 2021-2-2 15:00:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
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:

  1. Imports Autodesk.AutoCAD.Runtime
  2. Imports Autodesk.AutoCAD.ApplicationServices

  3. Public Class Commands
  4.   Implements IExtensionApplication

  5.   Public Sub Initialize() Implements IExtensionApplication.Initialize
  6.     AddHandler Application.DocumentManager.DocumentToBeDestroyed, AddressOf docBeginDocClose
  7.   End Sub

  8.   Public Sub Terminate() Implements IExtensionApplication.Terminate
  9.   End Sub

  10.   Public Sub docBeginDocClose(ByVal senderObj As Object, _
  11.                               ByVal docColDocActEvtArgs As DocumentCollectionEventArgs)
  12.     System.Diagnostics.Debug.Print("in docBeginDocClose")
  13.   End Sub

  14.   <CommandMethod("StopEvent")> _
  15.   Public Sub StopEvents()
  16.     Try
  17.       RemoveHandler Application.DocumentManager.DocumentToBeDestroyed, AddressOf docBeginDocClose
  18.     Catch ex As Exception
  19.       MsgBox("Error: " & ex.Message)
  20.     End Try
  21.   End Sub

  22. 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


论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|申请友链|小黑屋|手机版|Archiver|辽公网安备|晓东CAD家园 ( 辽ICP备15016793号 )  

GMT+8, 2021-3-8 21:12 , Processed in 0.102050 second(s), 12 queries , Gzip On, WinCache On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表