Proper disposal of COM interop objects in C# particularly MS Office applications

Raheel Khan picture Raheel Khan · May 10, 2012 · Viewed 9.6k times · Source

I am developing an application that relies heavily on multiple Microsoft Office products including Access, Excel, Word, PowerPoint and Outlook among others. While doing research on interop I found out that starting with VS2010 and .NET 4, we thankfully no longer have to go through the nightmares of PIAs.

Furthermore, I have been reading a lot of articles on proper disposal of objects, the most sensible one seemed to be this one.

However, the article is 5 years old and there are not many authoritative publications on the subject AFAIK. Here is a sample of code from the above link:

' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()

Marshal.FinalReleaseComObject(worksheet)

oWB.Close(SaveChanges:=False)
Marshal.FinalReleaseComObject(workbook)

oApp.Quit()
Marshal.FinalReleaseComObject(application)

What I want to know is by today's standards, how accurate is this and what should I look out for if I expect to support my application for the coming few years?

UPDATE: A link to some credible articles would be highly appreciated. By the way, this is not a server side application. This will be running in computer labs where we have users interact with office products that we instantiate for them.

FOUND IT: This three-part article is probably the closest to an authoritative account I would expect to find.

Answer

Peter Ritchie picture Peter Ritchie · May 10, 2012

Objects should be disposed automatically by the GC after the object goes out of scope. If you need to release them sooner, you can use Marshal.ReleaseComObject http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx