Release COM components

  • Thread starter Thread starter Nenad Dobrilovic
  • Start date Start date
N

Nenad Dobrilovic

Is it really necessary to release COM components from Office PIA, when you
don't need them anymore by invoking Marshal.ReleaseComObject(..)?

I found various and contradictory advices on this topic on the web. In my
opinion, since Office PIA is always returning a new references to its
interfaces as returning values from its methods, it is not necessary to
explicitly release it. Am I right?
 
No, that's not correct. In many cases unless you do use
Marshal.ReleaseComObject() you don't know when the objects are actually
released, you can get memory leaks and in the case of Word objects for
WordMail you can get kernel32 errors.

You do have to be careful as to when you call Marshal.ReleaseComObject()
because it releases all references to an object, even copies or different
instances of the object. For example call Marshal.ReleaseComObject() on an
Inspector passed to a class or method and not only that copy but the
original object are released and attempts to use the object result in an
invalid RCW error.

Only call Marshal.ReleaseComObject() when you are completely finished with
an object and any copies/instances of the object.

Another reason to call Marshal.ReleaseComObject() is the default 256 RPC
channel limit to Exchange. If you end up with that many or more current
objects instantiated, for example in a loop, then you will get errors back
when trying to instantiate any additional objects. That applies even to
implicit objects internally instantiated due to dot operators. Setting the
instances to null often isn't enough to release RPC channels due to the
indeterminate nature of when the GC runs. In those cases often the only way
to complete a loop is to explicitly call to Marshal.ReleaseComObject() and
then to GC.Collect().
 
Thanks a lot. Does it mean that implementing a Dispose pattern for a wrapper
classes (InspectorWrapper, ExplorerWrapper, etc) is a good idea?
 
I prefer not to use Dispose unless something calls it directly. In my
experiments with Dispose I've seen it not fire until after Outlook
disappeared from the UI, so you never know when it will be called. I prefer
to control things myself so I usually implement a "kill' method that I call.
 
Back
Top