1

I have written some C# programs that read from Excel files and output Excel files. However, I have noticed that at the end of the day I have a LOT of Excel processes still running after the programs have terminated and all files have been closed. Here is how I am handling the file creation and closing:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
...
wb.Close(true, saveDirectory + "\\" + reportName, false);
xlApp.Quit();
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xlApp);
this.Close();

Am I missing something? Any advice is appreciated.

Regards.

Kevin
  • 1,252
  • 6
  • 32
  • 50
  • I'd say that looks pretty straight forward. Perhaps you could write a short Console program that loops through 1000 or so itterations while watching the processes on your PC. My guess is something not shown in the `...` section could be causing your problem. –  Aug 24 '12 at 13:33
  • I think you should find your answer here http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c-sharp – MiiisterJim Aug 24 '12 at 13:46

1 Answers1

4

Your code is not releasing all COM references (e.g. xlApp.Workbooks.Add creates a reference to a Workbooks object that is never released). Therefore the Excel instance does not close, as described in this KB article, and discussed at length in numerous StackOverflow questions.

The Excel instances will eventually shut down after your process has terminated, when COM detects that there hasn't been a ping from the client for a while.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • I have changed `Marshal.ReleaseComObject(wb); ` to `while (Marshal.ReleaseComObject(wb) != 0) { Marshal.ReleaseComObject(wb);}` Will that do the trick? – Kevin Aug 24 '12 at 16:34
  • @Kevin - no, that won't be enough. It doesn't release the Workbooks object you reference using `xlApp.Workbooks.Add`. Also you should use `try/finally` to ensure you release objects even if an exception is thrown. – Joe Aug 24 '12 at 22:45