Does *every* Excel interop object need to be released using Marshal.ReleaseComObject?

試著忘記壹切 提交于 2019-11-27 19:21:06

I believe you would have to call ReleaseComObject on each COM object. Since they're not garbage-collected, the parent-child hierarchy doesn't really come into the equation: even if you release the parent object it does not decrement the reference count on any child objects.

You should call Marshal.ReleaseComObject on every COM object you use in your code, not just the main application object.

No. You don't have to release a single COM object. See this answer: Clean up Excel Interop Objects with IDisposable

To sum up the answer: The garbage collector will take care of them when it feels like it except if your program crash. What you need to be aware is:

  1. Running your app in DEBUG mode might delay/prevent the cleanup of COM object.
  2. Stopping the debugger (from within visual studio) will prevent the clean up of COM object. It is as if you crashed the app.
  3. If you close the debugged app properly, you will see that all COM objects are released. Also, running your app in Release mode and closing it properly will also release all COM objects.

Now if you want to release all COM object right after your method call ended, then you can Simply call GC.Collect(); GC.WaitForPendingFinalizers();

But you need to call this OUTSIDE the method who created the COM object. Again, this might not work as expected if you are debugging the app but it will work in Release mode.

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