Background Excel Thread not getting killed C #

You must work with Excel Interop. I can successfully open and read from an excel file, but closing it, the background process for this excel is not killed. I tried using several solutions from previous SO links, but no luck! So my question is: how to kill the background process?

The following is the UPDATED CODE that I am currently using:

Excel.Application application = new Excel.Application();

var workbooks = application.Workbooks;
Excel.Workbook workbook = workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
var rows = range.Rows;

// Some business logic  

for (int row = 2; row <= rows.Count; row++)
{
   //Read the data from the excel
}

// Some business logic

//close the excel
rows.Clear();
cell.Clear();
range.Clear();

workbook.Close(false);
application.Quit();

while (Marshal.FinalReleaseComObject(rows) != 0) { }
while (Marshal.FinalReleaseComObject(cell) != 0) { }
while (Marshal.FinalReleaseComObject(range) != 0) { }
while (Marshal.FinalReleaseComObject(worksheet) != 0) { }
while (Marshal.FinalReleaseComObject(workbook) != 0) { }
while (Marshal.FinalReleaseComObject(workbooks) != 0) { }
while (Marshal.FinalReleaseComObject(application) != 0) { }

rows = null;
cell = null;
range = null;
worksheet = null;
workbook = null;
workbooks = null;
application = null;
GC.Collect();
GC.WaitForPendingFinalizers();

Following the code above , I get the following exception in my debugger :

watch the 'application' in the VS debugger

Any help on this would be appreciated.

+4
source share
2 answers

range.Rows.Count, " 2 COM-". .

:

var rows = range.Rows
for (int row = 2; row <= rows.Count; row++)
{
   //Read the data from the excel
}
rows.Clear(); //rows is itself a range object 
0

, Excel, :

  • Excel- try-finally . finally .
  • Marshal.FinalReleaseComObject COM , , ref .
  • COM- . range, worksheet workbook ..
  • COM ( ) GC.Collect() GC.WaitForPendingFinalizers(). , COM-, .
0

All Articles