How to release/close the COM object

  • Thread starter Thread starter Mullin Yu
  • Start date Start date
M

Mullin Yu

as subject.

i instantiate a COM object at my c# application like below

IDMObjects.Library oLib = new IDMObjects.LibraryClass();

should i need to close it or set it to nothing/null to release resources.
e.g.
oLib = null

or something else

thanks!

mullin
 
Setting the local reference to null will not make any difference. You
can try using Marshal.ReleaseComObject().



Mattias
 
A warning from my own experience:
You can try using Marshal.ReleaseComObject()

....after which ALL references to that COM object will become invalid,
not only the reference passed to ReleaseComObject().
 
then, should i need to release the object?

at vb, we will set to nothing, and i don't know should i do so in c# when
calling com object


Dmitriy Lapshin said:
A warning from my own experience:
You can try using Marshal.ReleaseComObject()

...after which ALL references to that COM object will become invalid,
not only the reference passed to ReleaseComObject().
 
From KB317109:
call
System.Runtime.InteropServices.Marshal.ReleaseComObject(thecomobject);
thecomobject=null;
GC.Collect();

to force a release of the COM object. As others have said, other variables
that reference it will lose their reference, due to the RCW layer (runtime
callable wrapper) - as this method tells the RCW to release it, which
decrements *its* reference count to zero, which is the only thing that the
actual COM object itself is bothered about because that's what interfaces
it. Beware of the 'double-dot' syndrome - if you call
thecomobject.AMethod();

then you're ok, but if you call
thecomobject.APropertyThatsAlsoACOMObject.AMethod()
then you're referencing APropertyThatsAlsoACOMObject which will become a
hidden variable in the RCW and thus you'll never be able to release it. The
solution is to create an actual variable in your program for this
intermediary and do it in two steps, you can then use the aforementioned
method on it. (This bugged me for ages... see KB317109)
 
Back
Top