Visual Studio Tools For Office (VSTO) 2010 Outlook 加载项完成后如何清理

How to clean up after a Visual Studio Tools For Office (VSTO) 2010 Outlook Add-In completes

Microsoft 有一个简单的 VSTO 2010 Outlook 加载项演练,它完美地说明了我在我支持的更复杂的加载项中看到的问题。这是演练的 link:

FirstOutlookAddin Walkthrough

下面是我复制到 C# VSTO 2010 Outlook 加载项项目中的演练代码:

using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace FirstOutlookAddIn
{
    public partial class ThisAddIn
    {
        private Outlook.Inspectors inspectors;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            inspectors = this.Application.Inspectors;
        inspectors.NewInspector +=
            new Microsoft.Office.Interop.Outlook
                   .InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    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 = "Added Text";
                mailItem.Body = "Added Text to Body";
            }
        }
    }

    #region VSTO generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }      
    #endregion
}
}

我遇到的问题是将此代码与 Entrust 结合使用以发送加密电子邮件,然后撤回电子邮件并在编辑后重新发送。一旦我重新发送它(在召回和编辑之后),它就会破坏消息,当我尝试打开它时,我收到以下错误:

Sorry, we're having trouble opening this item. this could be temporary, but if you see it again you might want to restart Outlook. An error occurred in the underlying security system. An internal error occurred.

我几乎可以肯定,问题在于本地使用的一个或多个对象没有被垃圾收集器自动清理,但我不确定如何强制垃圾收集器(GC) 进行清理,使其正常工作。我一直在尝试将本地对象设置为 null,并且发现了一些讨论调用的帖子:

GC.Collect();
GC.WaitForPendingFinalizers();

也一直在尝试,但到目前为止运气不佳。谁能提供一些关于如何解决这个问题的建议?

如果你想从堆中清除未使用的 COM 对象,你需要调用 GC 两次。例如:

 GC.Collect();
 GC.WaitForPendingFinalizers();
 GC.Collect();
 GC.WaitForPendingFinalizers();

但更好的方法是使用 MSDN 中的 System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. This is particularly important if your add-in attempts to enumerate more than 256 Outlook items in a collection that is stored on a Microsoft Exchange Server. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects 文章。