15.7 Release a COM Component Quickly


Problem

You need to ensure that a COM component is removed from memory immediately, without waiting for garbage collection to take place. Or, you need to make sure that COM objects are released in a specific order.

Solution

Release the reference to the underlying COM object using the static Marshal.ReleaseComObject method and passing the appropriate RCW.

Discussion

COM uses reference counting to determine when objects should be released. When you use an RCW, the reference will be held to the underlying COM object even when the object variable goes out of scope. The reference will be released only when the garbage collector disposes of the RCW object. As a result, you can't control when or in what order COM objects will be released from memory.

To get around this limitation, you can use the Marshal.ReleaseComObject method. For example, in the ADO example in recipe 15.6, you could release the underlying ADO Recordset and Connection objects by adding these two lines to the end of your code:

 Marshal.ReleaseComObject(rs); Marshal.ReleaseComObject(con); 
Note  

Technically, the ReleaseComObject method doesn't actually release the COM object, it just decrements the reference count. If the reference count reaches 0 (zero), the COM object will be released. However, if you have multiple pieces of code using the same instance of a COM object, they will all need to release it before it will be removed from memory.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net