Tuesday, July 18, 2006

How do you release COM objects in c# ?

How do you release COM objects?
Consider calling Marshal.ReleaseComObject in a finally block to ensure that COM objects referenced through a runtime callable wrapper (RCW) release properly even if an exception occurs.
When you reference a COM object from ASP.NET, you actually maintain a reference to an RCW. It is not enough to simply assign a value of null to the reference that holds the RCW, and instead you should call Marshal.ReleaseComObject. This is of most relevance to server applications because under heavy load scenarios, garbage collection (and finalization) might not occur soon enough and performance might suffer due to a build up of objects awaiting collection.
You do not need to call ReleaseComObject from Windows Forms applications that use a modest number of COM objects that are passed freely in managed code.

The garbage collector can efficiently manage the garbage collection for these infrequent allocations.

A common pitfall when releasing COM objects is to set the object to null and call GC.Collect followed by GC.WaitForPendingFinalizers.

You should not do this because the finalization thread takes precedence over the application threads to run the garbage collection. This can significantly reduce application performance.

Snippet from article found at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/ScaleNetChapt13.asp

No comments: