Need Clarification On Answer For Cleaning Up Excel Interop Objects Properly

In regards to the answer to the question here by Hans Passant... Clean up Excel Interop Objects with IDisposable ...

He enlightened me to the fact that I don't need to follow the two dot rule... declaring all com objects so I can release via Marshal.ReleaseComObject when done with them. So now I understand I can just call GC.Collect and GC.WaitForPendingFinalizers after my Excel code and all objects will be released properly. For one, I think that is great and will reduce the length of macros I write in c# but I was in the habit of releasing objects as soon as I was done with them to minimize memory usage while the macro ran. Should I be concerned with cleaning up objects as I go or is it ok to just do a cleanup at the end of the macro like Hans suggested? I usually work with huge files and my macros will create many com objects to complete a task.


I was in the habit of releasing objects as soon as I was done with them to minimize memory usage while the macro ran. Should I be concerned with cleaning up objects as I go or is it ok to just do a cleanup at the end of the macro like Hans suggested?

As a general rule, release any resource as soon as you are done with it. The more expensive and/or scarce the resource, the more important that becomes. That is true of database connections, memory, file handles, etc.

It is also valid for references to COM objects.

Having said that, performing

GC.Collect();
GC.WaitForPendingFinalizers();

is a sensible thing to do in order to release any references that your as-soon-as-feasible cleanup may have caught.

There is a counter-argument to be made, which you can apply using common sense and looking at your own situation. You end up writing more code to clean up every COM reference as you go. If you are not creating an undue amount of COM objects before reaching a point where you can clean up, it might be worth opting for simpler code (eg using double-dots), knowing that you are temporarily consuming more resources than you absolutely need to.

链接地址: http://www.djcxy.com/p/35654.html

上一篇: 使用IDisposable清理Excel互操作对象

下一篇: 需要澄清答案正确清理Excel互操作对象