Posted by: Cirilo Meggiolaro | 10/22/2008

Releasing COM objects

Some concepts first

Every time a COM object is instantiated from a .NET client, the common language runtime creates a wrapper called RCW (stand for Runtime Callable Wrapper).

The RCW is the proxy responsible for marshal the calls between the .NET managed code and the COM unmanaged object and also keeps a counter used to determine the number of references pointers to that particular COM object.

Exactly one RCW is created for each COM object. If new references pointers are added to the object, the RCW counter is incremented.

Once created the RCW will release all reference pointers of the COM object only when the counter reaches zero again and a NullReferenceException will be thrown.

So keep in mind that you need in some way to decrement the counter when your application doesn’t need to consume the object anymore.

Solution

To accomplish that, you can invoke the following method under the System.Runtime.InteropServices namespace:

Marshal.ReleaseComObject(o);

The method above accepts a COM object as a parameter and retrieves the updated counter value.

If you want to completely remove all the reference pointers of a specific COM object you may either create a loop to decrement the number of reference pointers until it reaches zero or invoke the following method that will perform the same task internally:

Marshal.FinalReleaseComObject(o);

Exceptions

1. ArgumentException – thrown from both methods when the parameter is not a valid COM object. The ReleaseComObject also throws the same exception when the object is a null reference;

2. ArgumentNullException – thrown only from FinalReleaseComObject method when the parameter object is a null reference.

 
Keep your application healthy and don’t forget the basic concept: Create your objects as late as possible and release them as early as possible.

For complete details about interoperating with unmanaged code, click here!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: