What is the importance of using Marshal.ReleaseComObject when interacting with MailItems in Outlook?
I refer to the walkthrough on creating a C# VSTO Outlook AddIn at https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-creating-your-first-vsto-add-in-for-outlook?view=vs-2019
Where they have an example of modifying the exiting selected mail item's subject and body.
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
mailItem.Subject = "This text was added by using code";
mailItem.Body = "This text was added by using code";
}
}
}
The example ends without any mention of releasing the mail item object using Marshal.ReleaseComObject.
But in the .Net API Reference at https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.releasecomobject?view=netframework-4.8, they mentioned:
You should use this method to free the underlying COM object that holds references to resources in a timely manner or when objects must be freed in a specific order.
So apparently there are some consequence if we fail to use Marshal.ReleaseComObject on the MailItem we are referencing?
Is there a specific use case where not using Marshal.ReleaseComObject will lead to problem?
Thanks
If you don't call Marshal.ReleaseComObject, the object will be released as some later undermined point by the Garbage Collector. Normally, it is not a problem - you usually need to be careful and not leave the release to chance when processing a large number of items. In this particular case, you will be fine without Marshal.ReleaseComObject unless you want to make sure that the item is released in case it is updated externally and you don't want the Outlook Object Model to end up with a stale object.
Note that Marshal.ReleaseComObject on the mailItem variable will not be enough - you need to be careful about implicit variables, e.g. when you use a multiple dot notation. Some .Net operators also end up with implicit variables, and as is one of them (as well as is):
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
object item = Inspector.CurrentItem;
Outlook.MailItem mailItem = item as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
mailItem.Subject = "This text was added by using code";
mailItem.Body = "This text was added by using code";
}
Marshal.ReleaseComObject(mailItem);
}
Marshal.ReleaseComObject(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With