Cleaning up COM objects

  • Thread starter Thread starter Frank Rizzo
  • Start date Start date
F

Frank Rizzo

I've seen code that in addition to calling
System.Runtime.InteropServices.Marshal.ReleaseComObject on all the
allocated COM objects also call GC.Collect. Do I need to do that, or is
it overkill? This is in a Console Application situation.

Example:

oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
oXL = null;
GC.Collect(); //do I need this too?
 
Frank,

The call to the static Collect method on the GC class is excessive. The
important thing is that you released the COM object. Calling Collect at
that point will just do a GC, which will clean up the wrappers, and any
other items in memory that are slated for GC.

Generally speaking, you shouldn't have to make the call to Collect if
you call ReleaseComObject correctly.

Hope this helps.
 
to add to paldino's contribution releasecomobject is necessary especially
for office interop

--
________________________
Warm regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
Professional VSTO.NET - Wrox/Wiley
The O.W.C. Black Book with .NET
www.lulu.com/owc, Amazon
Blog: http://www.msmvps.com/blogs/alvin
-------------------------------------------------------


Nicholas Paldino said:
Frank,

The call to the static Collect method on the GC class is excessive.
The important thing is that you released the COM object. Calling Collect
at that point will just do a GC, which will clean up the wrappers, and any
other items in memory that are slated for GC.

Generally speaking, you shouldn't have to make the call to Collect if
you call ReleaseComObject correctly.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Frank Rizzo said:
I've seen code that in addition to calling
System.Runtime.InteropServices.Marshal.ReleaseComObject on all the
allocated COM objects also call GC.Collect. Do I need to do that, or is
it overkill? This is in a Console Application situation.

Example:

oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
oXL = null;
GC.Collect(); //do I need this too?
 
Back
Top