Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

3.30. Releasing a COM Object ThroughManaged Code

Problem

You need to release a COM object from managed code without forcing a garbage collection to occur.

Solution

Use the static ReleaseComObject method of the Marshal class:

int newRefCount = System.Runtime.InteropServices.Marshal.ReleaseComObject(COMObj);

where COMObj is a reference to the runtime callable wrapper (RCW) of a COM object.

Discussion

If the COM object is holding on to resources that need to be released in a timely manner, we will want to decrement the reference count on the COM object as quickly as possible, once we’ve finished using the COM object and have set it to null. The GC needs to run in order to collect the unreferenced RCW around our COM object, thereby decrementing the reference count on the COM object. Unfortunately, there is no guarantee that the GC will run in order to collect the RCW anytime in the near future.

To solve this problem, we could call GC.Collect ourselves to try to free the RCW, but this might be overkill. Instead, use the ReleaseComObject method to manually force the RCW to decrement its reference count on the COM object without having to force a collection to occur.

The static ReleaseComObject method returns an int indicating the current reference count contained in the RCW object after this method has finished decrementing its reference count. Remember that this method decrements the reference count contained in the RCW, not the COM object’s reference count. When the RCW reference count goes ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata