如何“释放”Microsoft.Office.Interop.Word.Application wordApp实例?

时间:2012-06-09 18:44:51

标签: c# memory-management garbage-collection

什么是"免费"的替代品?这个对象?它通常在调用.Exit()方法调用时发生,但在这种情况下,我不能这样做,因为应该关闭单词应用程序实例的用户。我想过wordApp = null或致电GC.Collect();什么是最好的解决方案?为什么?提前谢谢。

我目前正在使用它:

   public static void Free()
    {
        if (wordApp != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
            GC.Collect();
        }
    }

3 个答案:

答案 0 :(得分:3)

确保正确释放Interop对象的最积极的方法是使用从Releasing COM Objects改编的双Collect - WaitForPendingFinalizers模式:

Marshal.ReleaseComObject(wordApp);
wordApp = null;
GC.Collect(); 
GC.WaitForPendingFinalizers(); 
GC.Collect(); 
GC.WaitForPendingFinalizers(); 
  

托管世界和非托管世界之间的一个互操作区域需要特别小心,就是在完成它们时干净地释放COM对象。在前面的示例中,我们设法使用标准垃圾收集实现了我们想要的所有行为。唯一的小改进是两次调用GC.Collect以确保在第二次扫描时收集了可用于收集但在第一次扫描中幸存的任何内存。

答案 1 :(得分:3)

一种不那么激进的方法就是这样

        // Make sure to exit app first
        object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
        object originalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat;
        object routeDocument = false;

        ((_Application)wordApp).Quit(ref saveOption, ref originalFormat, ref routeDocument);

        if (wordApp!= null)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);

        // Set to null
        wordApp= null;

请确保所有文件已关闭或关闭并保存!

答案 2 :(得分:-1)

From MSDN

要解决ReleaseComObject返回的值大于零的情况,可以在执行ReleaseComObject的循环中调用该方法,直到返回的值为零:

Dim wrd As New Microsoft.Office.Interop.Word.Application
Dim intRefCount As Integer
Do 
  intRefCount = System.Runtime.InteropServices.Marshal.ReleaseComObject(wrd)
Loop While intRefCount > 0
wrd = Nothing