title: Excel Interop CustomDocumentProperties in foreach Causes Hang
body: <p>I have read the page <a href="https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects">How do I properly clean up Excel interop objects?</a> 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. </p>
  
  <p>This code below works and doesn't hang.</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>The problem is that once the code changes to this it hangs.</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Any ideas as to why the foreach there seems to cause issues?</p>