gpt4 book ai didi

c# - 如何 "free"Microsoft.Office.Interop.Word.Application wordApp 实例?

转载 作者:太空宇宙 更新时间:2023-11-03 20:25:17 24 4
gpt4 key购买 nike

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

我目前正在使用这个:

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

最佳答案

确保正确释放 Interop 对象的最积极的方法是使用双重 CollectWaitForPendingFinalizers 模式,改编自 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.

关于c# - 如何 "free"Microsoft.Office.Interop.Word.Application wordApp 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10963621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com