如何在.net中处理事件时释放所有COM对象

本文关键字:释放 COM 对象 处理事件 net | 更新日期: 2023-09-27 18:01:25

我在c#中使用COM Excel应用程序类。我处理了WorkbookBeforeClose。但是现在我不能正确地释放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()

如何在.net中处理事件时释放所有COM对象

内存管理在。net中是自动的。自己显式调用Marshal.ReleaseComObject()是错误的。这不仅是因为太早这样做很容易使RCW崩溃,而且还因为引用计数通常是隐藏的。索引器和事件是比较棘手的。一个丢失的ReleaseComObject调用就足以使它退回到负责处理它的垃圾收集器。GC需要一些时间来释放内存(和引用计数)是一个特性,而不是一个bug。

如果你真的,真的想让COM服务器按需退出,而不是让垃圾收集器处理它,那么将所有引用设置为null,取消订阅事件处理程序并调用GC.Collect()。不需要ReleaseComObject调用。查看这篇博文,了解专业人士的见解。

我通过修改closeExcel方法中的这些代码行来修复我的代码:

if (application != null)
{
   application.WorkbookBeforeClose -= new Excel.AppEvents_WorkbookBeforeCloseEventHandler(application_WorkbookBeforeClose);
   application.Quit();
   Marshal.ReleaseComObject(application);
   GC.Collect();
   GC.WaitForPendingFinalizers();
   process.WaitForExit(100);
}

我认为问题出在垃圾收集上。My Object没有完全收集