.net – Can’t release Excel COM object in .NET

comdisposeexcelnet

I have created a tool that imports an excel sheet. The excel COM object is created during the lifetime of the app. I have applied the MVP pattern to my tool so that VIEW and Presenter are seperating the UI and logic.

The vIEW that is a WinForm is having a Dispose() method due inheritance from From class, which is overriden in the Deisgner code.

protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
        _presenter.Dispose();
    }

Thats literally where I insert my dispose call o my presenter, which itself is a managed code, but yet contains unmanaged COM objects.

The presenter is then trying to release the COM object by doing this:

public void Dispose()
    {
        Int32 countDown = 1; 
        while (countDown > 0)
            countDown = Marshal.ReleaseComObject(_excelObj);
    }

If I open the app without importing anything, the Excel process disappears after closing teh app. Otehrwise if the app is used to import a sheet, the excel object doesn't let go anymore and remains in memory., even afte rthe job is sucesfully executed or cancelled.

I have found a good link that helped me further, but the problem still remains:
How do I ensure that objects are disposed of properly in .NET?

Thanks for help,

Best Answer

Try using FinalReleaseComObject instead of ReleaseComObject. Note that FinalReleaseComObject will not need to be used in a loop the way ReleaseComObject does.

For a more in-depth explanation, take a look at this reply to another question since there are likely other Excel objects you can be clearing up to ensure references aren't held. That entire question is helpful but the linked post in particular should sum things up.