How can I verify that Excel interop objects are cleaned up properly?
I'm instantiating Excel interop objects in my project. I know that special effort is required to clean up those objects (see this question). Is there any automated way to verify that the cleanup was done properly?
To elaborate, I'm aware that when cleanup is not done properly, Excel.exe may continue running after Application.Quit is called. However, it is not clear to me whether that is a reliable test condition. Also, since a lingering Excel.exe process is merely a symptom of the true dysfunction, it would seem preferable to use a test condition closer to the root cause, if such a condition exists.
When finished using the Excel objects, I call this method "just in case" - mostly picked from the link at SO you also refer to:
public static void CloseExcel()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (_range != null)
{
Marshal.FinalReleaseComObject(_range);
_range = null;
}
if (_workSheet != null)
{
Marshal.FinalReleaseComObject(_workSheet);
_workSheet = null;
}
if (_workBook != null)
{
_workBook.Close(false, String.Empty, false);
Marshal.FinalReleaseComObject(_workBook);
_workBook = null;
}
if (_application != null)
{
try
{
_application.Quit();
}
Marshal.FinalReleaseComObject(_application);
_application = null;
}
}
It runs so quickly that I really don't care if it could be optimized or not.
链接地址: http://www.djcxy.com/p/35718.html