在C#中释放Excel互操作对象的最佳实践是什么?

问题描述:

我基本上具有一个将excel文件转换为文本文件的功能.结构如下.我所关心的是最后一部分?杀死优秀人才是最佳实践吗?

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();
}

更新:

我有以下版本的Final

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?

最佳做法是在COM对象的全部上调用Marshal.ReleaseComObject(object name)Marshal.FinalReleaseComObject(object name).当然,根据项目的 size ,它很快就会变得笨拙.您上面发布的代码在较小的规模上应该可以正常工作,并且如果您密切注意创建COM对象的时间/位置.我在此处此处此处.

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.