How to Terminate Applicationclass Object After Quitting in C#

Problem:
I have developed an application in Visual Studio C# that will read and write contents on an excel document. After I'm done coding, I've found several instances of the EXCEL application in the System's Task Manager.

I've googled and found this: http://support.microsoft.com/kb/Q317109

Unfortunately, it might be confusing for others, so here's what worked for me.

Don't do this:

workBook = excelApp.Workbooks.Open(docname, m, m, m, m, m, m, m, m, m, m, m, m, m, m);

Try to break the declaration like this:


//member variables
private Microsoft.Office.Interop.Excel.ApplicationClass excelApp;
private Workbooks workBooks;
private Workbook workBook;
private Worksheet workSheet;

//declared inside a method
excelApp = new ApplicationClass();
Missing m = Missing.Value;
workBooks = excelApp.Workbooks;
workBook = workBooks.Open(docname, m, m, m, m, m, m, m, m, m, m, m, m, m, m);


Then after you have finished editing your document, you have to close, dispose the object and reclaim the memory it used.


excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBooks);
GC.Collect();
GC.WaitForPendingFinalizers();


Note that we run ReleaseComObject on both workbook and workbooks object. Explanation is on the link from microsoft above.

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.