How to release/close the COM object

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
 
M

Mattias Sjögren

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



Mattias
 
D

Dmitriy Lapshin [C# / .NET MVP]

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().
 
M

Mullin Yu

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().
 
B

Bonj

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top