Excel Interop CustomDocumentProperties in foreach Causes Han

本文关键字:Causes Han foreach in Interop CustomDocumentProperties Excel | 更新日期: 2023-09-27 18:33:18

我已阅读页面如何正确清理 Excel 互操作对象? 但我遇到了一个我无法弄清楚的问题。有一种情况是嵌入了 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。我什至尝试在每个对象的每个元帅之前调用双 GC 线,但它仍然挂起。此代码是从处理释放属性来源的工作簿的事件访问的。

关于为什么那里的foreach似乎会引起问题的任何想法?

Excel Interop CustomDocumentProperties in foreach Causes Han

我不确定您的问题,可能与释放 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;
    }
}