views:

371

answers:

2

This is a follow on question to How to properly clean up excel interop objects in c#.

The gyst is that using a chaining calls together (eg. ExcelObject.Foo.Bar() ) within the Excel namespace prevents garbage collection for COM objects. Instead, one should explicitly create a reference to each COM object used, and explicitly release them using Marhsal.ReleaseComObject().

Is the behaviour of not releasing COM objects after a chained call specific to Excel COM objects only? Is it overkill to apply this kind of pattern whenever a COM object is in use?

+2  A: 

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.

Ian Kemp
...for some definition of "necessary". On process shutdown (or app domain unload, if that happens first), I believe all RCWs (runtime callable wrappers) that haven't yet gotten destroyed will get released. Unfortunately, there aren't strong guarantees around them properly getting destroyed and having all of their finalizers executed. Among other things, if destroying a COM object takes longer than 2 seconds, the CLR will terminate the entire queue of finalizers being executed on that thread.
Reuben
@Reuben, please read the question, the answer is 100% correct with regards to the question being asked, however great intrinsic details about COM has nothing to do with this question.
Akash Kava
+4  A: 

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.

Mattias S
Very good points RE: why you must cleanup office interop objects
Anonymous Type