Nice clean way to dispose of COM object (Such as Excel/Word)
Posted: 10/21/2005 3:25:16 PM
By: Comfortably Anonymous
Times Read: 2,384
0 Dislikes: 0
Topic: Programming: .NET Framework
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
Rating: (You must be logged in to vote)