Search code examples
c#comcom-interopexcel-interop

How to dispose of Excel.Application class correctly


I have a real pain of an issue whereas the Excel.Application() does not want to get released, no matter what. Even after a new class is instantiated and disposed immediately afterwards, it still appears in the process list.

if (_ExcelApp == null)
    _ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Dispose();

public void Dispose()
{
    if (_ExcelApp != null)
    {
        try
        {
            _ExcelApp.Quit();
            Marshal.FinalReleaseComObject(_ExcelApp);
        }
        catch (Exception) { }
            _ExcelApp = null;
    }
}

Please help!


Solution

  • It do not release because not all COM objects which are related to _ExcelApp released. If you provide all piece of code, it may be more clearer.

    Workbooks wb =_ExcelApp.Workbooks;
    Workbook book = wb.Add();
    

    Then in try catch:

              try
                {
                  book.Close();
                  Marshal.ReleaseComObject(book);
                  wb.Close();
                  Marshal.ReleaseComObject(wb);
                  _ExcelApp.Quit();
                  Marshal.FinalReleaseComObject(_ExcelApp);
                }
            catch (Exception) { }
                _ExcelApp = null;
        }
    

    _ExcelApp.WorkBooks.Add(); create new WorkBook and you do not release this object. Also it create Workbooks object which also have to be released.

    As I have mentioned earlier will be better if you show all code(if it is possible of course)