gpt4 book ai didi

c# - foreach 中的 Excel Interop CustomDocumentProperties 导致挂起

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:56 27 4
gpt4 key购买 nike

我已阅读页面 How do I properly clean up Excel interop objects?但我遇到了一个我无法弄清楚的问题。有一种情况是嵌入了 Excel 实例并且我的插件存在导致挂起。我已经释放了所有 COM 对象,并按照针对 VSTO 的建议尝试了双 GC 收集和 GC 等待线。

下面这段代码有效,不会挂起。

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;
}

问题是一旦代码更改为此它就会挂起。

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;
}

我不明白为什么访问 customProperties 中的对象会导致挂起,但注释掉 foreach 可以防止挂起,即使内部没有执行任何操作或调用 FinalReleaseComObject 也是如此。我什至尝试在每个对象的每个编码(marshal)之前调用双 GC 行,但它仍然挂起。此代码是从处理释放属性所来自的工作簿的事件中获取的。

关于为什么 foreach 似乎会导致问题的任何想法?

最佳答案

我不确定您的问题,可能与释放 COM 对象有关。我认为 CLR 不喜欢您释放 CustomDocumentProperties,而它仍然附加到 WordDocument 实例。

这是我在多个生产环境中使用的代码,没有任何问题。我记得使用 DocumentProperties 时出现的很多问题和错误,但这段代码似乎很稳定。

它获取 DocumentProperty,这就是您稍后需要清理的全部内容。

private object GetDocumentProperty(_Word.Document wordDocument, string name)
{
try
{
return wordDocument.CustomDocumentProperties[name];
}
catch (ArgumentException)
{
//
// Key not found.
//
return null;
}
}

关于c# - foreach 中的 Excel Interop CustomDocumentProperties 导致挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303015/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com