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 cod...
https://www.czetsuyatech.com/2021/07/c-terminate-excel.html
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:
Then after you have finished editing your document, you have to close, dispose the object and reclaim the memory it used.
Note that we run ReleaseComObject on both workbook and workbooks object. Explanation is on the link from microsoft above.
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.
Post a Comment