Releasing the iTunes Windows COM from Managed Code

Q: How do I properly release the iTunes for Windows COM object from managed code?

A: The Microsoft .NET Framework common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). A single RCW is created for each COM object, and it maintains a reference count that is incremented every time a COM interface pointer is mapped to it. When the reference count reaches zero, the runtime releases all its references on the unmanaged COM object. Therefore, if all references have not been released on the RCW, the COM object will not be released.

To release COM objects correctly you must call the .NET Framework Marshal.ReleaseComObject method. This method decrements the reference count of the supplied RCW. You should use this method to free the underlying COM object as shown in Listing 1 for the iTunes COM:

Listing 1: Releasing the iTunes COM using the .NET Marshal.ReleaseComObject method.

using System.Runtime.InteropServices;
using iTunesLib;

iTunesApp iTApp;

...
Marshal.ReleaseComObject(iTApp); // release the iTunes COM
iTApp = null;

Document Revision History

Date Notes
2008-08-21 First Version

Posted: 2008-08-21


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.