Reputation: 1593
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);
Upvotes: 1
Views: 250
Reputation: 7092
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);
Upvotes: 2