处置 Microsoft.Office.Interop.Word.Application [英] Disposing of Microsoft.Office.Interop.Word.Application
问题描述
(该帖子的一些后续内容(仍未得到答复):https://stackoverflow.com/q/6197829/314661)
(Somewhat of a follow on from the post (which remains unanswered): https://stackoverflow.com/q/6197829/314661)
使用以下代码
Application app = new Application();
_Document doc = app.Documents.Open("myDocPath.docx", false, false, false);
doc.PrintOut(false);
doc.Close();
我正在尝试以编程方式打开和打印文件.
I am attempting to open and print a file programmatically.
问题是每次我运行上述代码时都会启动一个新的 WINWORD.exe 进程,显然这会很快吃掉所有内存.
The problem is each time I run the above code a new WINWORD.exe process is started and obviously this quickly eats up all the memory.
应用程序类似乎不包含 dispose/close 或类似方法.
The application class doesn't seem to contain a dispose/close or similar method.
经过一番研究,我(意识到)并将代码更改为以下内容.
After a bit of research I (realized) and changed the code to the following.
Application app = new Application();
_Document doc = app.Documents.Open(fullFilePath + ".doc", false, false, false);
doc.PrintOut(false);
doc.Close();
int res = System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
int res1 = System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
我可以看到剩余的引用计数为零,但进程仍然存在?
And I can see the remaining reference count is zero but the processes remain?
PS:我使用的是 Microsoft.Office.Interop 库的第 14 版.
PS: I'm using Version 14 of the Microsoft.Office.Interop library.
推荐答案
也许尝试设置 doc = null
并调用 GC.Collect()
Perhaps try setting doc = null
and calling GC.Collect()
编辑,不是我自己的代码,我忘记了我从哪里得到的,但这是我用来处理 Excel 的,它可以完成工作,也许您可以从中收集到一些东西:
Edit, not really my own code I forget where I got it but this is what I use to dispose of Excel, and it does the job maybe you can glean something from this:
public void DisposeExcelInstance()
{
app.DisplayAlerts = false;
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Quit();
if (workSheet != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
if (workBook != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
if (app != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
workSheet = null;
workBook = null;
app = null;
GC.Collect(); // force final cleanup!
}
这篇关于处置 Microsoft.Office.Interop.Word.Application的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!