How can I guarantee the MS Word process exits (using C# Interop library)?
My current approach:
// close word document ("doc")
((_Document)doc).Close(SaveChanges: WdSaveOptions.wdDoNotSaveChanges);
if (doc != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
doc = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
// close word application ("word")
((_Application)word).Quit(false);
if (word != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
word = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
// and here is how it fails
Process[] pname = Process.GetProcessesByName("WINWORD");
Assert.IsTrue(pname.Length == 0);
Sources:
c# MSOffice Interop Word will not kill winword.exe
Disposing of Microsoft.Office.Interop.Word.Application
Microsoft.Interop object won't quit or "release"
There is no need to use ReleaseComObject if you use the GC methods for swiping the heap. Also be aware, you need to call the GC methods twice:
Anyway, I always recommend using System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Office (Word) object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article. It is related to Outlook, but the same rules can be applied to any Office aplication (including Word).