When you automate a Microsoft Office application from Microsoft Visual Basic .NET or Microsoft Visual C# .NET, the Office application does not quit when you call the Quit method.
To make sure that the Office application quits, make sure that your automation code meets the following criteria:
- Use System.Runtime.InteropServices.Marshal.ReleaseComObject when you have finished using an object. This decrements the reference count of the RCW.
- To release the reference to the variable, set the variable equal to Nothing or Null.
- Use the Quit method of the Office application object to tell the server to shut down.
Private Sub NAR(ByVal o As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
Catch
Finally
o = Nothing
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oApp As New Excel.Application()
Dim oBooks As Excel.Workbooks = oApp.Workbooks
Dim oBook As Excel.Workbook = oBooks.Add
Dim oSheet As Excel.Worksheet = oApp.ActiveSheet
NAR(oSheet)
oBook.Close(False)
NAR(oBook)
NAR(oBooks)
oApp.Quit()
NAR(oApp)
Debug.WriteLine("Sleeping...")
System.Threading.Thread.Sleep(5000)
Debug.WriteLine("End Excel")
End Sub
C#
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch {}
finally
{
o = null;
}
}
Troubleshooting
Note that if you follow the steps that are described in the “Steps to Reproduce the Behavior” section, and the server still does not shut down, you can use the GC.Collect() method and the GC.WaitForPendingFinalizers() method after you release the last object. Because the runtime performs garbage collection on the RCW, the GC.Collect() method forces the garbage collector to run and might release any references that the RCW still has. The GC.Collect() method tries to reclaim the maximum memory that is available. Note that this does not guarantee that all memory will be reclaimed.