I have read the page How do I properly clean up Excel interop objects? but I am running into an issue I can't figure out. There is a situation where an Excel instance is embedded and my addin is present causing a hang. I've released all of the COM objects and tried the double GC collection and GC wait lines as suggested for VSTO.
This code below works and doesn't hang.
public static string GetCustomProperty(dynamic document, string propertyName)
{
string returnVal = string.Empty;
dynamic customProperties = document.CustomDocumentProperties;
if (customProperties != null)
{
// Nothing
}
Marshall.FinalReleaseComObject(customProperties);
return returnVal;
}
The problem is that once the code changes to this it hangs.
public static string GetCustomProperty(dynamic document, string propertyName)
{
string returnVal = string.Empty;
dynamic customProperties = document.CustomDocumentProperties;
if (customProperties != null)
{
foreach (dynamic property in customProperties)
{
Marshall.FinalReleaseComObject(property);
}
}
Marshall.FinalReleaseComObject(customProperties);
return returnVal;
}
I can't figure out why accessing the objects in customProperties is causing a hang, but commenting out the foreach prevents the hang even when nothing is done inside or FinalReleaseComObject is called. I even tried calling the double GC lines before each marshal of every object and it still hangs. This code is reached from events that handle releasing the workbook the properties come from.
Any ideas as to why the foreach there seems to cause issues?