Excel Interop CustomDocumentProperties in foreach Causes Hang
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?
I am not sure about your issue, possibly it is related to releasing the COM objects. I don't think the CLR likes you releasing the CustomDocumentProperties
, while it is still attached to the WordDocument
instance.
This is the code I am using in multiple production environments without any problems. I can remember a lot of issues and errors working with DocumentProperties
, but this code seems to be stable.
It gets the DocumentProperty
so that is all you have to clean up later.
private object GetDocumentProperty(_Word.Document wordDocument, string name)
{
try
{
return wordDocument.CustomDocumentProperties[name];
}
catch (ArgumentException)
{
//
// Key not found.
//
return null;
}
}
链接地址: http://www.djcxy.com/p/35716.html