Avoiding COM-Related Memory Leaks with Excel
Recently I was handed a combined WCF service and Excel 2007 add-in done in C#. project. Although most .NET developers assume garbage collection is handled automatically, it is definitely not true when working with COM objects assume, particularly Office objects. Below is some distilled knowledge when working with Excel (Office) COM object:
- Avoid more than a single dot when setting references to COM objects
- Avoid using references that can not be released explicitly
- Call FinalReleaseAndNull on all COM objects when finished and as soon as feasible
- Call Garbage Collection (GC) twice at the end of a routine
- Avoid passing objects in such a way it could prevent GC, where objects are passed and become part of other process and objects, becoming unrecoverable.