Close Excel after use

  • Thread starter Maciej Pietruszka
  • Start date
M

Maciej Pietruszka

My app read from Excel file using Excel's COM dll

I create Excel object by:

Excel.Application ExcelObj = new Excel.Application();

and next make it inivisible:
ExcelObj.Visible = false;

All works great, but I saw in Task Manager that "excel" process still
exist even my app closed.
Seems to my app create "excel" process and doesnt dispose it

How can I do that programically?

Rgs
Maciej
 
N

Nicholas Paldino [.NET/C# MVP]

Maciej,

You must call Quit before you release the reference to the Excel
application object. This causes Excel to shut down (it is an out of process
COM server) when you release the final reference. Once you call Quit, you
need to call the static ReleaseComObject method on the Marshal class to
release the reference.

You need to be careful if you use properties on the application object
(which I am sure you are) which return other objects. The object model is
such that most every object returned has a reference to the main application
object (so yours is not the only one). Because of this, you need to make
sure that you pass every object exposed through a property or returned
through a method to the ReleaseComObject method on the Marshal class. DON'T
do something like this:

// Set the value on a range.
ExcelObj.Workbooks.Item(1).Worksheets.Item(1).Cells(1, 1).Value = "hello";

This causes SIX com objects to be exposed, most of which have a
reference to the Application object.

Now, if the instance of excel that you are using is pretty localized in
your app (you use it in the course of a method invocation, and don't hold
onto it for a long time), then you ^could^ get away with this, forcing a
garbage collection at the end of your method. However, this could have a
negative impact on your performance, so you would have to consider this
approach very carefully.

Hope this helps.
 
M

Maciej Pietruszka

Yeah you helped me a lot.
Many thanx!

That was what I've looked for.

Rgs
Maciej
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top