I'm running into the classic scenario where, when creating Word COM objects in .NET (via the Microsoft.Office.Interop.Word assembly), the WinWord process won't exit even though I'm properly closing and releasing the objects.
I've narrowed it down to the use of the Word.Documents.Add() method. I can work with Word in other ways without a problem (opening documents, modifying contents, etc) and WinWord.exe quits when I tell it to. It's once I use the Add() method (and only when adding a template) that the process is left running.
Here is a simple example which reproduces the problem:
Dim oWord As New Word.Application()
oWord.Visible = False
Dim oDocuments As Word.Documents = oWord.Documents
Dim oDoc As Word.Document = oDocuments.Add(Template:=CObj(sTemplatePath), NewTemplate:=False, DocumentType:=Word.WdNewDocumentType.wdNewBlankDocument, Visible:=False)
' dispose objects
oDoc.Close()
While (Marshal.ReleaseComObject(oDoc) <> 0)
End While
oDoc = Nothing
While (Marshal.ReleaseComObject(oDocuments) <> 0)
End While
oDocuments = Nothing
oWord.Quit()
While (Marshal.ReleaseComObject(oWord) <> 0)
End While
oWord = Nothing
GC.Collect()
As you can see I'm creating and disposing the objects properly, even taking the extra step to loop Marsha.ReleaseComObject until it returns the proper code. Working with the Word objects is fine in other regards, it's just that pesky Documents.Add that is causing me grief. Is there another object that gets created in this process that I need to reference and dispose of? Is there another disposal step I need to follow? Something else? Your help is much appreciated :)
Update:
I tried GC.Collect at the end of the disposal step but still no luck.
Update 2:
I've narrowed the problem down to the use of custom templates. When I invoke Documents.Add(...) I specify a custom template for the new document. If I don't do this and instead invoke Add() with no parameters, then the problem does not happen.