Unsure when to call ReleaseComObject

Add-in Express™ Support Service
That's what is more important than anything else

Unsure when to call ReleaseComObject
 
David Taylor




Posts: 10
Joined: 2008-05-01
Part of the functionality I'm implementing requires opening a .MSG file that has been pulled from a server and is now stored locally. I'm using the CreateItemFromTemplate() method as follows:


Outlook.MailItem mailItem = null;
try
{
  mailItem = (Outlook.MailItem)OutlookApp.CreateItemFromTemplate("d:\tmp\test.msg", Type.Missing);
  mailItem.Display((object)false);
}
catch
{
}
finally
{
}


When should I call Marshall.ReleaseComObject()? I don't think I can do it in my code above, because the Inspector will still be displayed and be active.

Should I track which mailItems I've created myself (perhaps by entryID) and subscribe to the Inspector.Close event. I could then compare entryIDs and if it's a mialItem I've created myself call ReleaseComObject().
Posted 03 Jun, 2008 22:00:12 Top
Sergey Grischenko


Add-in Express team


Posts: 7233
Joined: 2004-07-05
Hi David.

I would call the Marshal.ReleaseComObject in the finally block.
Posted 04 Jun, 2008 10:15:24 Top
David Taylor




Posts: 10
Joined: 2008-05-01
Sergey,

I should have phrased my question a little better. Generally speaking I'm thinking I should ReleaseComObject in the finally block of whatever method instantiates those objects. As per the "rules", I shouldn't release objects that I get access to via event args etc. Even if those objects subsequently remain open (such as the above example), as far as my code is concerned I've finished with them, so it's appropriate to call ReleaseComObject.

Just trying to establish some sensible coding practices and guidelines for the team up front.

Thanks
David
Posted 05 Jun, 2008 20:27:25 Top
Andrei Smolin


Add-in Express team


Posts: 18830
Joined: 2006-05-11
Hi David,

Yes, correct. When you're done with COM objects that you (!) instantiated, you'd better release them. Yes, you may choose not to release them, but this can lead to hardly reproducible errors. As to COM objects supplied in event parameters, Add-in Express releases them after invoking every event handler. That's why we insist that you do not release them.

That is, you can use the caller-takes-care strategy in your add-ins. In the manual, you can find the FolderPath Property Value in Outlook 2000 and XP chapter, which demonstrates this approach. Also you may want to read a post on our blog: see http://www.add-in-express.com/creating-addins-blog/2006/08/17/outlook-not-closing/. Note that for add-ins targeting Outlook 2000 and XP, you must release all COM objects.

All in all, when I look at how .NET makes us treat COM objects, I always think about programming in unmanaged C++. In this language, you have to take care about COM reference counting yourself. Br-r-r!


Andrei Smolin
Add-in Express Team Leader




Posted 06 Jun, 2008 09:01:12 Top