我在C#中使用COM Excel应用程序类。我处理了WorkbookBeforeClose
。但是现在我无法正确释放COM对象。如何在.NET中处理事件时释放所有COM对象
请注意,我在处理此事件之前设法正确地释放了COM对象,并且在注释该部分代码时,我的应用程序正常工作。
哪些COM对象没有从内存中释放,以及如何正确释放它?
编辑: 我做了什么:
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;
}
应用停留在行process.WaitForExit()
。
你能告诉我们你做了什么吗?所以我们可以看到有什么问题? –