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

后端 未结 3 1562
谎友^
谎友^ 2020-12-05 04:23

Edit

Please see also How do I properly clean up Excel interop objects?. I recently came across this question, and it provided a lot of insight into

3条回答
  •  星月不相逢
    2020-12-05 05:03

    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.

提交回复
热议问题