Releasing a COM Object

Mike_R

Well-known member
Joined
Oct 20, 2003
Messages
316
Location
NYC
Hi guys, in MSKB 317109, MSFT shows a way of releasing a COM Object using the following code:

Code:
Sub NAR(ByVal o As Object)
     This sub cleanly releases the COM Automation Object.
     Source: [url]http://support.microsoft.com/?kbid=317109[/url]
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
    Catch
    Finally
       o = Nothing
   End Try
End Sub
The interesting thing is that since o is declared ByVal, the Finally line, setting o = Nothing, really does not do anything.

Chaning o to be ByRef would seem to be the correct way to go, however under Option Strict this implicit coercion is not permitted.

The solutions to this seem onerous:

(1) Use Overloading for every possible Excel Object type imaginable.
(2) Use Option Strict Off
(3) Kill the o = Nothing line within the NAR() routine and simply call
Code:
NAR(oExcelObject)
oExcelObject = Nothing

I suppose that #3 is best, but the whole point of the NAR() routine is to encapsulate the process of Releasing a Com Object in one call...

Any ideas on how this might be handled better?

Thanks in advance :),
Mike
 
Ok, Ill answer my own post, I guess...

I gave this a lot of thought (and did a good deal of testing) and although
Code:
Marshal.ReleaseCOMObject(oExcelObject)
oExcelObject = Nothing
is good, I actually have found it better to use
Code:
oExcelObject = Nothing
GC.Collect()
There are caveates abound when it comes to realeasing COM Objects, but I wrote up my findings as best I could in a tutorial that can be found here, if anyone is interested... (You can skip to the "Cleanup" section.)
 
Back
Top