none
Need to call ReleaseComObject when iterating through MailItems? RRS feed

  • Question

  • I'm trying to figure out where my app may be leaking. Here's some code similar to what we are doing.

    Do I need to call Marshal.ReleaseComObject() on any of the items in the code below, and if so, which ones?

    private Outlook.Folder _inbox;
    public Outlook.Folder Inbox { get { return _inbox; } }
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        _inbox = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
    }
    public void SomeMethod()
    {
        Outlook.Items items = Inbox.Items;
        Outlook.MailItem item = items.Find("MyObject") as Outlook.MailItem;
        while (item != null)
        {
            // do something
            item = items.FindNext() as Outlook.MailItem;
        }
    }

    Friday, April 12, 2013 1:35 AM

Answers

  • Release the item variable. Others are not so important - they are only retrieved once, so the GC will take care of them eventually.

    Item on the other hand is retrieved potentially hundreds of times in the same loop, so it is a good idea to release it on every iteration.


    Dmitry Streblechenko (MVP)
    http://www.dimastr.com/redemption
    Redemption - what the Outlook
    Object Model should have been
    Version 5.4 is now available!

    Friday, April 12, 2013 5:13 AM

All replies

  • You don't have to, but it would be a good idea, especially if you are working with a folder in the online mode and processing a large number of items.

    Dmitry Streblechenko (MVP)
    http://www.dimastr.com/redemption
    Redemption - what the Outlook
    Object Model should have been
    Version 5.4 is now available!

    Friday, April 12, 2013 1:58 AM
  • Should I call Marshal.ReleaseComObject() on:

    items ?

    each item before the FindNext()?

    _inbox when the app is shutting down?

    Friday, April 12, 2013 2:21 AM
  • on every outlook object: MailItem, Items, Folder, UserProperty, etc.
    Friday, April 12, 2013 4:09 AM
  • Release the item variable. Others are not so important - they are only retrieved once, so the GC will take care of them eventually.

    Item on the other hand is retrieved potentially hundreds of times in the same loop, so it is a good idea to release it on every iteration.


    Dmitry Streblechenko (MVP)
    http://www.dimastr.com/redemption
    Redemption - what the Outlook
    Object Model should have been
    Version 5.4 is now available!

    Friday, April 12, 2013 5:13 AM
  • Thank you for your detailed answer of why I should release the item variable. I wil add that to our code and hopefully it will fix the x8c520009 and x80020009 Exceptions we are getting.
    Friday, April 12, 2013 5:23 PM