[英]How to “free” an Microsoft.Office.Interop.Word.Application wordApp instance?
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. 通常会在调用
.Exit()
方法时发生,但是在这种情况下,我无法执行此操作,因为应关闭word应用程序实例的用户。 I thought to do wordApp = null
or call GC.Collect();
我想做
wordApp = null
或调用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 Collect
– WaitForPendingFinalizers
pattern, adapted from Releasing COM Objects : 确保Interop对象被正确释放的最积极的方法是使用双重
Collect
– WaitForPendingFinalizers
模式,该模式适用于释放COM对象 :
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.
在托管世界和非托管世界之间,您需要特别注意的一个互操作区域是在使用完COM对象后,干净地释放它们。 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.仅有的一点改进是调用了
GC.Collect
两次,以确保可用于收集但在第一次扫描中幸存的所有内存在第二次扫描中被收集。
A less agressive way to do it is like this 这样一种不太激进的方式就是这样
// 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;
Make sure however that all documents have been closed and or closed and saved! 但是,请确保已关闭所有文档,或者已关闭并保存所有文档!
To address those situations when the value returned by ReleaseComObject is greater than zero, you can call the method in a loop that executes ReleaseComObject until the returned value is zero: 要解决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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.