0

Possible Duplicate:
Killing an interop Application process

I am using Microsoft.Office.Interop.Excel in order to get data from excel. Even though i clear the COM objects it still leaves some instances of EXEL.EXE in the background.Check my code below.

finally
        {
            if (cells != null) Marshal.FinalReleaseComObject(cells);
            if (range != null) Marshal.FinalReleaseComObject(range);
            if (sheets != null) Marshal.FinalReleaseComObject(sheets);
            if (workSheet != null) Marshal.FinalReleaseComObject(workSheet);
            if (excelWorkBook != null)
            {
                excelWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
                Marshal.FinalReleaseComObject(excelWorkBook);
            }
            if (excelWorkbooks != null) Marshal.FinalReleaseComObject(excelWorkbooks);

            if (excel != null)
            {
                excel.Quit();
                Marshal.FinalReleaseComObject(excel);
            }
            cells = null;
            range = null;
            sheets = null;
            workSheet = null;
            excelWorkBook = null;
            excelWorkbooks = null;
            excel = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

        }

Please tell me where I have gone wrong.

Community
  • 1
  • 1
sharmila
  • 1,493
  • 5
  • 23
  • 42
  • A quite extensive cleanup, however 'sheets' is missing in the finalreleasecomobject list? – Me.Name Jun 22 '12 at 05:15
  • Please check the edited code above..Still EXEL.EXE remains in the background. – sharmila Jun 22 '12 at 06:19
  • If there is edited code in your post, 'sheets' isn't cleaned in it. I've posted an answer as well, because it's easier to use markup in it ;) – Me.Name Jun 22 '12 at 08:14

1 Answers1

1

The only variable that isn't released is sheets, defined as:

   sheets = excelWorkBook.Worksheets;

Then again, sheets is never used, so it can be left out completely, because worksheet is assigned as:

   workSheet = (Worksheet)excelWorkBook.Worksheets["Sheet1"]; //doesn't use sheets, so sheets can be omitted

or if sheets is needed, if it's released as well my tests show the excel process closing (before application end, after application end it was always closed successfully)

   Marshal.FinalReleaseComObject(sheets);
Me.Name
  • 12,259
  • 3
  • 31
  • 48