
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Releasing a COM Object Through Managed Code
|
189
Solution
Use the static ReleaseComObject method of the Marshal class:
int newRefCount = System.Runtime.InteropServices.Marshal.ReleaseComObject(COMObj);
where COMObj is a reference to the runtime callable wrapper (RCW) of a COM object.
Discussion
If the COM object is holding on to resources that need to be released in a timely
manner, you will want to decrement the reference count on the COM object as soon
as possible after you’ve finished using the COM object and have set it to
null. The
garbage collector needs to run in order to collect the unreferenced Runtime Callable
Wrapper (RCW) around your COM object, thereby decrementing the reference
count on the COM object. Unfortunately, there is no guarantee that the garbage col-
lector will run in order to collect the RCW anytime in the near future.
To solve this problem, you could call
GC.Collect yourself to try to free the RCW, but
this might be overkill. Instead, use the
ReleaseComObject method to manually force
the RCW to decrement its reference count on the COM object without having to
force a collection to occur.
The static
ReleaseComObject method returns an int indicating the current reference
count contained in the RCW object after this method has finished decrementing its
reference count. ...