Life cycle of a COM object in C#-is Release() called?

C

cmbardon

I have a C# application that uses a C++ COM exe server, and I've
noticed some strange behaviour with the life cycle of the object. In
my .net app, I create an instance of the COM object (generated RCW),
and am able to deal with methods and connection points without any real
problems. The object is a member variable of the main client form.
When the client application is closed however, the COM server is not
always advised, meaning that the exe server process is not ended. I
was able to rectify this by adding a call to Marshal.ReleaseComObject()
to my code, but now I'm wondering what the issue was in the first
place.

My guess at this point is that for COM objects, the Release() method of
the IUnknown interface is called when the object is deleted by the
garbage collector. For some reason, when my client application exits,
the garbage collector isn't always run on its memory, meaning that the
call to Release() never happens. Is this anywhere even close to
correct? Is there something else that I'm missing? At this point I'm
just trying to understand what's happening rather than just guessing,
and I'm sure someone else here has run into a similar issue.

Thanks!

Chris
 
L

Lebesgue

You have to release the COM object by calling
Marshal.ReleaseComObject(object comObject);
 
G

Guest

Lebesque is correct...

AND the best way to deterministically release the COM object is to implement
an IDisposable pattern on the class that uses the com object. If you
implement IDisposable and use the com containing class in a "using" block
then your COM server will get released when you exit the using block - no
matter how you exit it; aka by completing all steps or by throwing an
exception...
 

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