Marshal.ReleaseComObject(...) issues
I use said invocation to release some Excel objects after I'm done. Is it necessary to set references to null afterwards (like in the following code) ?
var dateCol开发者_开发百科 = sheet1.get_Range("C4", "C" + rowOffset);
dateCol.NumberFormat = "Text";
Marshal.ReleaseComObject(dateCol);
dateCol = null;
This is what I always use and it works very well
using Excel = Microsoft.Office.Interop.Excel;
Excel.ApplicationClass _Excel;
Excel.Workbook WB;
Excel.Worksheet WS;
try
{
_Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
WB = _Excel.Workbooks.Open("FILENAME",
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);
//do something
}
catch (Exception ex)
{
WB.Close(false, Type.Missing, Type.Missing);
throw;
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);
}
Do a
System.Runtime.InteropServices.Marshal.FinalReleaseComObject
On all referenced Excel objects
精彩评论