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.

2
  • 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. Commented Aug 24, 2012 at 13:33
  • I think you should find your answer here stackoverflow.com/questions/158706/… Commented Aug 24, 2012 at 13:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have changed Marshal.ReleaseComObject(wb); to while (Marshal.ReleaseComObject(wb) != 0) { Marshal.ReleaseComObject(wb);} Will that do the trick?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.