如何“免费”一个Microsoft.Office.Interop.Word.Application wordApp实例? [英] How to "free" an Microsoft.Office.Interop.Word.Application wordApp instance?

查看:356
本文介绍了如何“免费”一个Microsoft.Office.Interop.Word.Application wordApp实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以免费这个对象?它通常在调用 .Exit()方法时被调用,但在这种情况下,我不能这样做,因为应该关闭单词应用程序实例的用户。我想要做 wordApp = null 或者调用 GC.Collect(); 什么是最好的解决方案,为什么?



我现在使用这个:

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


解决方案

确保Interop对象被正确释放的最积极的方式是使用双 Collect - WaitForPendingFinalizers 模式, 发布COM对象

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




托管世界与非托管世界之间的一个互动区域,其中你需要特别小心的是,当你完成它们时,干净地释放COM对象。在前面的例子中,我们设法实现了我们使用标准垃圾回收所需的所有行为。唯一轻微的增强是调用 GC.Collect 两次,以确保任何可用于收集但在第一次扫描中存活的内存都是在第二次扫描时收集的。



What are alternatives to "free" this object? it normally happens when call the .Exit() method is called, but in this case, I can't do this because the user that should close the word application instance. I thought to do wordApp = null or call GC.Collect(); what's the best solution and why? thanks in advance.

I'm using this currently:

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

解决方案

The most aggressive way to ensure that the Interop object is properly released is the using the double CollectWaitForPendingFinalizers pattern, adapted from Releasing COM Objects:

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

One area of interop between the managed world and the unmanaged world in which you need to be especially careful is in cleanly releasing COM objects when you're done with them. In the foregoing examples, we managed to achieve all the behavior we wanted using standard garbage collection. The only slight enhancement was to call GC.Collect twice to ensure that any memory that was available for collection but survived the first sweep was collected on the second sweep.

这篇关于如何“免费”一个Microsoft.Office.Interop.Word.Application wordApp实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆