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

ali*_*ari 2 c# com excel memory-management

我在 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;
    }
Run Code Online (Sandbox Code Playgroud)

应用程序暂停 在线process.WaitForExit()

Han*_*ant 5

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

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