This question already has an answer here:
I have a function basically to convert an excel file to text file. The structure is like following. What I am concerned is the Finally part? Is it a best practise to kill the excel?
Excel.Application excel=new Excel.Application();
Excel.Workbook wb=excel.Workbooks.Open(…);
Try
{
…
Foreach(Excel.Worksheet sheet in wb.Sheets)
{
…
Marshal.RealseComObject(sheet);
}
…
}
Catch()
{
}
Finally
{
wb.Close(false, missing, missing);
while (Marshal.ReleaseComObject(wb)!=0)
{
}
wb=null;
excel.Quit();
while (Marshal.ReleaseComObject(excel)!=0)
{
}
excel=null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Update:
I have following version of Finally
Finally{
wb.close(false, missing, missing);
excel.application.quit();
excel.quit();
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(excel);
GC.Collect();
GC.WaitForPendingFinalizers();
}
Which one is better (make more sense)? I have checked all the links here, but there is no finally answer, everybody's answer is sightly difference. I am not sure which one is the best?
The best practice is to call
Marshal.ReleaseComObject(object name)
orMarshal.FinalReleaseComObject(object name)
on all of yourCOM
objects. Of course, depending on the size of your project, this can become unwieldy very quickly. The code you have posted above should work just fine on a smaller scale and if you pay close attention to when/where your are creating theCOM
objects. I found some further reading for you here, here, here and here.