Managing COM Object Lifetime in a Garbage-Collected Environment
Managing COM Object Lifetime in a Garbage-Collected Environment
COM objects are responsible for managing their own lifetimes using a standard reference counting scheme. .NET objects, on the other hand, don't need to perform this mundane and error-prone task. The same is true for COM components written or used in Visual Basic, but the difference with .NET is that the Common Language Runtime (CLR) uses garbage collection to manage object lifetime. In a garbage-collected environment, objects are not freed as soon as the last client is finished using it, but at some undetermined point afterward.
To make the use of COM components in managed code as seamless as possible, the CLR encapsulates them in wrapper objects known as Runtime-Callable Wrappers (RCWs). RCWs are responsible for handling all transitions between COM and .NET, such as data marshaling, exception handling, and the subject of this articleobject lifetime. To prevent managed clients of a COM object from engaging in reference counting, an RCW's lifetime is controlled by garbage collection (just like any other managed object). Each RCW caches interface pointers for the COM object it wraps, and internally maintains its own reference count on these interface pointers. When an RCW is garbage-collected, its finalizer releases all of its cached interface pointers. Thus, a COM object is guaranteed to be alive as long as its RCW is alive.
Because COM objects are often designed to be destroyed as soon as clients are finished using them, it can be problematic to keep COM objects alive until garbage collection releases them at some undetermined time. An example of a troublesome COM object is one that holds onto a limited resource, such as a database connection, and doesn't release it until it is destroyed.
In Visual Basic 6, a COM object could be immediately released by setting the object reference to Nothing (null). In managed code, however, setting an object to null only makes the original instance eligible for garbage collection; the object is not immediately released. One way to force the early release of a COM object wrapped by an RCW is to force the early garbage collection of the RCW. Once an RCW is eligible for collection, calling System.GC.Collect followed by System.GC.WaitForPendingFinalizers will do the trick.
Forcing garbage collection is not a quick operation, however, so a special API exists in the System.Runtime.InteropServices namespace for forcing an RCW to release its inner COM object before the RCW is collected: Marshal.ReleaseComObject. This static (Shared in VB .NET) method must be passed an RCW, and returns an integer representing the RCW's reference count on the wrapped COM object. For an RCW called obj, this method can be called in Visual Basic .NET as follows:
Marshal.ReleaseComObject(obj)
ReleaseComObject decrements the reference counts of any interface pointers cached once by the RCW, similar to what would happen if the RCW were collected. Because interface pointers inside RCWs are not reference-counted based on the number of .NET clients, calling ReleaseComObject once per RCW is usually enough. However, an interface pointer's reference count is incremented every time it crosses the boundary from unmanaged to managed code. It's rare that this occurs more than once, but to be absolutely sure that calling ReleaseComObject releases the underlying COM object, youshould call ReleaseComObject in a loop until the returned reference count reaches zero, as follows in C#:
while (Marshal.ReleaseComObject(obj) > 0) {}
Once the returned count reaches zero, the CLR is guaranteed to release all of the COM object's interface pointers that the RCW holds onto. (Whether the COM object's own reference count reaches zero is dependent on whether additional COM objects are holding onto its interface pointers.) Although the RCW remains alive until the next collection, it's just an empty wrapper unusable to any .NET clients. Attempting to call any member on an RCW after passing it to ReleaseComObject raises a NullReferenceException.
ReleaseComObject is only meant to be used if absolutely necessary. In many cases, you should be able to let the garbage collector take care of everything rather than complicating your code with explicit releasing.