How to properly clean up interop objects in C#

偶尔善良 提交于 2019-12-05 10:26:54

It's definitely more important to handle releases properly when dealing with Office applications than many other COM libraries, for two reasons.

  1. The Office apps run as out of process servers, not in-proc libraries. If you fail to clean up properly, you leave a process running.
  2. Office apps (especially Excel IIRC) don't terminate properly even if you call Application.Quit, if there are outstanding references to its COM objects.

For regular, in-proc COM libraries, the consequences of failing to clean up properly are not so dramatic. When your process exits, all in-proc libraries goes away with it. And if you forget to call ReleaseComObject on an object when you no longer need it, it will still be taken care of eventually when the object gets finalized.

That said, this is no excuse to write sloppy code.

COM objects are essentially unmanaged code - and as soon as you start calling unmanaged code from a managed application, it becomes your responsibility to clean up after that unmanaged code.

In short, the pattern linked in the above post is necessary for all COM objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!