no

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...

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.

Related

c# 3441419796356386681

Post a Comment Default Comments

Outsourcing

Are you looking for freelancers in the Philippines? Get in touch.

Donations

If you like what I do, you can support this channel by buying me a coffee. I would be grateful for your contribution! Your donations will help me create more FREE online courses and learning materials for programmers and remote workers.

item