Question

Trying to figure out why my EXCEL*32 process remains in use until both the my application AND the excel file are closed. I must be missing something after creation, it's like the application is holding onto the EXCEL *32 resource after this code. Any suggestions to get it to 'let go' after it's export operation is completed?

Also, I do not want to close the newly created Excel sheet, I just want to release the resource being used in relation to my actual .net application.

Application xls = new Application();
xls.SheetsInNewWorkbook = 1;

// Create our new excel application and add our workbooks/worksheets
Workbook Workbook = xls.Workbooks.Add();
Worksheet CrossoverPartsWorksheet = xls.Worksheets[1];

// Create our new excel application and add our workbooks/worksheets
Workbook Workbook = xls.Workbooks.Add();
Worksheet CrossoverPartsWorksheet = xls.Worksheets[1];

/////////////////////////////////////////
// < DO EXCEL EXPORT OPERATIONS HERE > //
/////////////////////////////////////////

// Release our resources.
Marshal.ReleaseComObject(Workbook);
Marshal.ReleaseComObject(CrossoverPartsWorksheet);
Marshal.ReleaseComObject(xls);
Was it helpful?

Solution

When you write

Workbook Workbook = xls.Workbooks.Add();

CLR creates RCW (Runtime Callable Wrapper) objects not only for Workbook, but for Workbooks collection too(coz you need object that then will be used for Add() method). And if CLR creates RCW object and you do not keep reference - you can't finalize it.

So, the main rule: You should avoid double-dot-calling expressions:

var workbooks = xls.Workbooks;
var workbook = workbooks.Add();

Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);

OTHER TIPS

Marshal.FinalReleaseComObject(xls) is what your looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top