Search code examples
c#winformsoutlook-addincomobjectaddin-express

When to correctly release Outlook COM-objects?


I know similar questions have been asked here, but I feel like I don't understand it correctly.

I have the following code for example:

Microsoft.Office.Interop.Outlook.Explorer expl = myOutlooApplication.ActiveExplorer();
if (expl.Selection.Count > 0)
{
    object selObject = expl.Selection[1];
    if (selObject is Microsoft.Office.Interop.Outlook.MailItem)
    {
        mailItem = (selObject as Microsoft.Office.Interop.Outlook.MailItem);
        this.myUserControl.MailItem = mailItem;
    }
}

As you can see, the MailItem gets passed to a property of myUserControl. MyUserControl will need to access this property later to extract some information from the MailItem.

Should I Marshal.ReleaseComObject() after passing the MailItem to myUserControl to reduce the reference counter of the RCW or is this too early?

EDIT: My problem is, that a .msg file will be opened from the file system. After closing the inspector, the user tries to open the file again, but it is locked and I am sure that the COM objects not being released properly is the cause for that.


Solution

  • Unless you have a documented memory leak linked to your COM objects, don't start messing with the Marshal COM methods. The RCW takes care of translating the garbage-collected world of .NET into the reference-counting world of COM, and generally does a good job of it.

    You might consider forcing it out with Marshal.FinalReleaseComObject at a point where you're certain that no managed references to the object are going to be accessed and the COM object consumes considerable resources. You might want to consider an IDisposable wrapper to translate that into .NET terms. You're certainly not in that position in the code you've shown - you know you've just passed a managed reference to the RCW to myUserControl and you're presumably expecting it to access that reference.

    .NET references to RCWs are not the type of references that COM counts.