I am using COM Excel Application class in C#. I handled the WorkbookBeforeClose
. But now I can't release the COM objects properly.
Note that I managed to release the COM objects properly before handling this event and when commenting that part of code, my application works properly.
What COM object is not released from memory and how to release it properly?
Edit: What I've done:
public void Init()
{
...
application = new Excel.Application();
application.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(application_WorkbookBeforeClose);
}
...
void application_WorkbookBeforeClose(Excel.Workbook Wb, ref bool Cancel)
{
if (WorkbookBeforeClose != null)
{
ExcelCloseEventArgs args = new ExcelCloseEventArgs();
WorkbookBeforeClose(this, args);
Cancel = args.Cancel;
}
else
Cancel = false;
}
...
private void closeExcel()
{
try
{
if (workbook != null)
{
workbook.Close(false);
}
}
catch (Exception e) { }
finally
{
if (workbooks != null)
Marshal.ReleaseComObject(workbooks);
if (workbook != null)
Marshal.ReleaseComObject(workbook);
}
try
{
if (application != null)
{
application.WorkbookBeforeClose -= handler;
application.Quit();
Marshal.ReleaseComObject(application);
Marshal.ReleaseComObject(handler);
process.WaitForExit();
}
}
catch (Exception e) { throw; }
finally
{
}
workbook = null;
workbooks = null;
application = null;
if (process != null && !process.HasExited)
process.Kill();
if (threadCulture != null)
Thread.CurrentThread.CurrentCulture = threadCulture;
initialized = false;
}
Application pauses In line process.WaitForExit()
.