Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# foreach中的Excel互操作CustomDocumentProperties_C#_Excel_Foreach_Interop - Fatal编程技术网

C# foreach中的Excel互操作CustomDocumentProperties

C# foreach中的Excel互操作CustomDocumentProperties,c#,excel,foreach,interop,C#,Excel,Foreach,Interop,我已经读了这一页,但我遇到了一个我无法理解的问题。在这种情况下,Excel实例被嵌入,而我的加载项存在,导致挂起。我已经发布了所有COM对象,并尝试了VSTO建议的双GC收集和GC等待行 下面的代码可以工作,不能挂起 public static string GetCustomProperty(dynamic document, string propertyName) { string returnVal = string.Empty; dynamic customProperties

我已经读了这一页,但我遇到了一个我无法理解的问题。在这种情况下,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会防止挂起,即使在内部没有任何操作或调用FinalEleaseComObject时也是如此。我甚至尝试在每个对象的每个封送之前调用双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;
    }
}

我试过你的方法,效果很好。奇怪的是,另一种方法现在也在起作用。我现在在另一台电脑上,所以我明天会继续测试,看看另一台电脑是否处于某种导致问题的奇怪状态。尽管我喜欢将COM对象传回调用方处理的想法,而不是更好地在调用的函数中释放它,这样更改可能会保持不变。好的。祝你好运,如果你需要帮助,请告诉我。