I have a Windows Forms app that opens an instance of Excel. If the user quits the app early, I want to make sure that this Excel instance has been quit. I tried calling the Excel instance's Quit()
method if the instance was not null
, like this:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.Run(form1);
form1.logFile.close();
if (form1.xlApp != null)
{
form1.xlApp.Quit();
}
}
}
But if I quit the Excel app in Task Manager and then close the GUI, I get this error:
System.Runtime.InteropServices.COMException (0x800706BA):
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
A check of (xlApp==null)
in the Immediate window showed that xlApp
was not null, even though there was no instance of Excel running.
So I tried removing the Quit()
line and using this instead:
Marshal.ReleaseComObject(form1.xlApp);
This worked fine for closing without error when the user quits the Excel app early, but if the instance is still running in Task Manager when the GUI is closed, the ReleaseComObject()
call does not end the Excel instance.