简体   繁体   中英

Do I have to close Word Interop Application?

I'm using the following code:

using MSWord = Microsoft.Office.Interop.Word;

.
.
.

MSWord.Application wordApp = new MSWord.Application();

MSWord.Document wordDoc = new MSWord.Document();

wordDoc = wordApp.Documents.Add(Template: oTemplatePath);

//do something with the Document... replace fields and so on...

wordApp.Visible = true;

the function then exits and my app is closing down, for example. Now the user can edit the open document, and save it or just close it.

Do I have to close the Application-Object (in terms of COM-Objects and so on) programmatically??? Or does this the Garbage collector?

If you want to correctly close / dispose COM Objects when using Microsoft.Interop you would want to use this method

System.Runtime.InteropServices.Marshal.ReleaseComObject( "Replace with your ComObject Here"); 

so for example if I have created an object named wordApp I would declare it like this and dispose it like the following

MSWord.Application wordApp = new MSWord.Application();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); 

This can give you an example of how to use ReleaseComObject Marshal.ReleaseComObject Method

You're ok. When you call new MSWord.Application(); a new Ms-Word process starts and manages the Document.

You don't have to worry. If you display the document to the user, when he closes the document all will be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM