ReleaseComObject() or not?
-
How do I know whether or not to call ReleaseComObject()? For example in the following code I call ReleaseComObject() on the Worksheet, it works fine, but I dont rearly know if this is correct or not. How would I know? Is there a rule that I need to follow?
try
{Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); string strWorkBook = @"C:\\zz\\Book1.xlsx"; Workbook workBook = excelApp.Workbooks.Open(strWorkBook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); int nSheets = workBook.Sheets.Count; Worksheet sheet = (Worksheet)workBook.Sheets\[1\]; // Do somthing with the Worksheet... Marshal.ReleaseComObject(sheet); workBook.Close(false, strWorkBook, null); Marshal.ReleaseComObject(workBook);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}“If I had asked people what they wanted, they would have said faster horses.” ― Henry Ford
-
How do I know whether or not to call ReleaseComObject()? For example in the following code I call ReleaseComObject() on the Worksheet, it works fine, but I dont rearly know if this is correct or not. How would I know? Is there a rule that I need to follow?
try
{Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); string strWorkBook = @"C:\\zz\\Book1.xlsx"; Workbook workBook = excelApp.Workbooks.Open(strWorkBook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); int nSheets = workBook.Sheets.Count; Worksheet sheet = (Worksheet)workBook.Sheets\[1\]; // Do somthing with the Worksheet... Marshal.ReleaseComObject(sheet); workBook.Close(false, strWorkBook, null); Marshal.ReleaseComObject(workBook);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}“If I had asked people what they wanted, they would have said faster horses.” ― Henry Ford
-
Don't agree to that. ReleaseComObject should only be called when absolutely required. Even then it's better to call FinalReleaseComObject. See http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx[^] Piet