Wednesday, October 18, 2006

Releasing COM components


Clean up after the use of com components ALLWAYS! Don't wait for the garbage collection to take action, free that memory asap. Ensure that the objects are released in a specific order.

To release use the Marshal.FinalReleaseComObject and pass the relevant RCW.

COM uses reference counting to determine when objects finally get released. RCW's cause the underlying COM object to hold onto the reference even when the object variable goes out of scope! The reference will be released only when the GC disposes of the RCW, thus you cannot control when or in what order COM objects are released from memory.

If there are several references held using Marshal.ReleaseComObject will need to be called several times. If you want to release them all in one go then use Marshal.FinalReleaseComObject this will set the reference count straight to zero.

No comments: