When to release object using Marshal.ReleaseComObject...

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

When to release object using Marshal.ReleaseComObject...
 
Paul Cross


Guest


The documentation states that the following:

"Add-in Express relies on the state of the COM object provided in this class member. That's why you must never release it. On the contrary, you must release every COM object obtained from this COM object.
To release a COM object, you use the System.Runtime.InteropServices.Marshal.ReleaseComObject method."

In the code shown below I'm obtaining a reference to a MailItem from ItemObj. Should I therefore use ReleaseComObject or not? The docs are confusing me!

public override void ProcessWrite(ADXCancelEventArgs e)
{
try
{
if (!IsConnected)
{
return;
}
MailItem mailItem = (MailItem)ItemObj;
// Do stuff with mailItem...
}
catch (Exception ex)
{
// Handle exception
}
finally
{
if (mailItem != null)
{
Marshal.ReleaseComObject(mailItem);
}
}
}

Thanks,
Paul
Posted 25 Sep, 2008 13:31:07 Top
Eugene Astafiev


Guest


Hi Paul,

What is the ItemObj? I don't see the declaration and initialization of this object.
Posted 26 Sep, 2008 04:48:50 Top
Andrei Smolin


Add-in Express team


Posts: 18825
Joined: 2006-05-11
Hi Paul,

You must not release mailitem because it shares the same Runtime Callable Wrapper (RCW) with itemObj. When you release mailitem, you effectively release itemObj and in this way disconnect it from events.

If, however, you access the Attachments property, it returns a COM object which you must release.


Andrei Smolin
Add-in Express Team Leader
Posted 26 Sep, 2008 10:07:23 Top
Paul Cross


Guest


Great. That's sorted it.

Thanks,
Paul
Posted 26 Sep, 2008 12:28:22 Top