C# VSTO Outlook 加载项 : What is a possible impact of not releasing the MailItem object

标签 c# outlook vsto outlook-addin office-addins

在 Outlook 中与 MailItems 交互时使用 Marshal.ReleaseComObject 的重要性是什么?

我引用了创建 C# VSTO Outlook 插件的演练,网址为 https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-creating-your-first-vsto-add-in-for-outlook?view=vs-2019

他们有一个修改现有选定邮件项目的主题和正文的示例。

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";
        }

    }
}

示例结束时没有提及使用 Marshal.ReleaseComObject 释放邮件项对象。

但在 https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.releasecomobject?view=netframework-4.8 的 .Net API 引用中,他们提到:

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.

那么,如果我们未能在我们引用的 MailItem 上使用 Marshal.ReleaseComObject,显然会有一些后果?

是否存在不使用 Marshal.ReleaseComObject 会导致问题的特定用例?

谢谢

最佳答案

如果您不调用 Marshal.ReleaseComObject,该对象将作为垃圾收集器稍后破坏的点被释放。通常,这不是问题 - 在处理大量项目时,您通常需要小心,不要随意放行。在这种特殊情况下,没有 Marshal.ReleaseComObject 就没问题,除非您想确保项目已发布以防它在外部更新并且您不希望 Outlook 对象模型结束有一个陈旧的对象。

请注意,mailItem 变量上的 Marshal.ReleaseComObject 是不够的 - 您需要注意隐式变量,例如当您使用多点表示法时。一些 .Net 运算符也以隐式变量结束,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);
}

关于C# VSTO Outlook 加载项 : What is a possible impact of not releasing the MailItem object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58927495/

相关文章:

html - Outlook 中的 HTML 电子邮件失真

excel - Excel文档级部署问题

c# - 如何自动化测试 Outlook Add-In?

c# - 在没有 Microsoft Interop 的情况下从 dotx 生成 docx

c# - 如何将 SQL Server 表拉入内存以便对其运行查询

c# - 与 fo-dicom 的存储 promise

javascript - 在 JS 中保留发送到 mailTo 的文本格式

excel - 查找主题以特定文本开头的电子邮件

c# - 此 C# 代码是否会因为寄存器或缓存中的值永远不会写回主内存而失败?

excel - 在 VSTO 中找不到从 XLStart 文件夹加载的所有插件