title: Outlook 2007 Add-in Memory Leak?
body: <p>I've created a simple Outlook 2007 add-in using C# which loops through a selection of Messages and examines their attachments.</p>
  
  <p>I'm running this add-in on a set of ~25,000 selected Messages.  Immediately, however, I notice the memory usage of Outlook (seen via perfmon) shooting up.  After running the add-in in debug mode, line-by-line, it is apparent that memory is assigned to Outlook upon the first instance of accessing a Message's Attachments collection.  This memory is <em>never</em> returned to the system; Outlook continues to eat memory until it hits ~1GB (after about 12,000 Messages), whereupon I receive an "out of memory or system resources" error.  Any ideas?</p>
  
  <p>Here's part of the code:</p>
  
  <pre><code>        for(int i = 1; i &lt;= objSelectedItems.Count; i++)
          {
              Object objMsg = objSelectedItems[i];
  
              //Only process if Item is a Message
              if (objMsg is Outlook.MailItem)
              {
                  Outlook.MailItem Msg = objMsg as Outlook.MailItem;
  
                  //The culprit: this allocates memory to Outlook which I can't get back
                  Outlook.Attachments objAttachments = Msg.Attachments;
  
                  //Perform some actual work here//
  
                  //Clean up Outlook objects; does not appear to give memory back to system
                  Msg.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
                  Marshal.ReleaseComObject(objAttachments);
                  Marshal.ReleaseComObject(Msg);
              }
  
              Marshal.ReleaseComObject(objMsg);
              GC.Collect();
              GC.WaitForPendingFinalizers();
          }            
  </code></pre>