在 C# 中自动删除 COM 事件处理程序
我有一个独立的 .exe COM 服务器和一个简单的 C# 测试程序,该程序启动服务器的实例并随后立即关闭它。就像魅力一样。但是,如果我关闭 C# 程序本身,我会在终结器运行期间收到异常,因为它试图从不再运行的 COM 服务器取消注册/取消通知 COM 事件接收器。
例外是
“mscorlib.dll 中发生了 System.Runtime.InteropServices.InvalidComObjectException' 类型的第一次机会异常”
以及调用堆栈:
mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.Unadvise() + 0x20 字节 mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.RemoveAll(System.Runtime.InteropServices.ComEventsSink 接收器) + 0x11 字节
mscorlib.dll!System.Runtime.InteropServices.ComEventsInfo.Finalize() + 0x18 字节
我可以通过在关闭服务器之前手动删除 COM 事件处理程序来修复此错误。即 myComServer.OnFunkyEvent -= OnFunkyEventHandler;然而,我发现这不优雅、容易出错并且乏味。所以问题是,我能否以某种方式手动触发 COM 事件的 RemoveAll() 调用,以便它不会在终结器中运行?
I have a standalone .exe COM server and a trivial C# test program that launches an instance of the server and closes it immediately afterwards. Works like a charm. However, if I close the C# program itself I get an exception during the finalizer run because it is trying to unregister/unadvise COM event sinks from the no longer running COM server.
The exception is
"A first chance exception of type System.Runtime.InteropServices.InvalidComObjectException' occurred in mscorlib.dll"
And the callstack:
mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.Unadvise() + 0x20 bytes mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.RemoveAll(System.Runtime.InteropServices.ComEventsSink sinks) + 0x11 bytes
mscorlib.dll!System.Runtime.InteropServices.ComEventsInfo.Finalize() + 0x18 bytes
I can fix this error by manually removing the COM event handlers before shutting down the server. I.e. myComServer.OnFunkyEvent -= OnFunkyEventHandler; However, I find this inelegant, error prone and tedious. So the question is, can I somehow trigger the RemoveAll() call for my COM events manually so it won't run in the finalizer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论