What is the best practise to relase Excel interop objects in C#? [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-12 02:46:16

问题


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?


回答1:


The best practice is to call Marshal.ReleaseComObject(object name) or Marshal.FinalReleaseComObject(object name) on all of your COM 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 the COM objects. I found some further reading for you here, here, here and here.



来源:https://stackoverflow.com/questions/19713082/what-is-the-best-practise-to-relase-excel-interop-objects-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!