View Light

Nice clean way to dispose of COM object (Such as Excel/Word)

When using an Excel, Word, or other Office COM object in your VB.NET or ASP.NET app, the seemingly trickiest part is getting that *&^&^$% COM object disposed when done. If not done right, then you end up with a bunch of orphaned EXCEL.EXE (or similar) instances hanging around in Task Manager.

Even weirder, there is a thing with COM objects where there will be multiple 'references' to the COM object. Until all those references are gone, you CANNOT terminate and dispose of the COM object. With the code below, you simply pass the COM object to it and it knocks out the references one by one until they are all gone, then disposes of the object. Works really nicely.

Make sure that any files opened by your COM object are closed before calling it, if you call it and still have an XLS or DOC (or whatever) file open, the reference for the open file cannot be killed. (The sub will return, but the object will still be floating out there.)  That's the one thing with COM objects, everything is done in more of a 'request' (Oh great COM object, I beg you to perform this action...) basis rather than an authoritive/imperative mode (As in 'You punk @$$ COM object, you WILL do what I tell you...), so you always have to keep that in mind and treat the COM object with proper respect and attitude or it will punk out on you and make your life miserable.

Also, make sure you have Imports System.Runtime.InteropServices.Marshal at the top of your code, as that's where the 'ReleaseComObject' method comes from.

    Protected Sub disposeCOMObject(ByVal comObject As Object)
        While ReleaseComObject(comObject) > 1
            ' Interate until no more references to COM object
        End While

        ' Collect memory now that the COM object has been disposed
        GC.Collect()
    End Sub
Reply
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: http://www.law.cornell.edu/uscode/17/107.shtml . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.