How to deallocate COM server object forcefully from C# .NET – Education Career Blog

Can I know how to deallocate COM server object forcefully from C# .NET if particular condion fails or the object is partially constructed?

The problem is I am using that COM server using DCOM mechanism; in the worst case, when the object is not created fully and I am coming out of application since failure, the COM object is still in memory (showed in COM+ Application component services). If its going beyond some limits, it leads to memory leak and crash. But if its manageable amount of failures, its getting deleted after some point of times.

Calculator.App objApp = new Calculator.App();

if( !obj.CanBeUsed() )
//how to deallocate the COM object objApp

There is a method GC.Collect() used by Garbase Collector to de-allocate from the heap memory forcefully. Whether I can use this method or .NET franework is giving anyother solution for this particular case?


Like this:



You should try Marshal.FinalReleaseComObject method.

The FinalReleaseComObject method
releases the managed reference to a
COM object. Calling this method is
equivalent to calling the
ReleaseComObject method in a loop
until it returns 0 (zero).

When the reference count on the COM
object becomes 0, the COM object is
usually freed, although this depends
on the COM object’s implementation and
is beyond the control of the runtime.
However, the RCW can still exist,
waiting to be garbage-collected.

The COM object cannot be used after it
has been separated from its underlying
RCW. If you try to call a method on
the RCW after its reference count
becomes 0, a InvalidComObjectException
will be thrown.

Leave a Comment