如何在Visual Studio Tools For Office (VSTO) 2010 Outlook Add-In完成后进行清理

3

Microsoft有一个简单的VSTO 2010 Outlook Add-In演示,完美地说明了我在支持的更复杂的Add-In中看到的问题。这是Walkthrough的链接:

FirstOutlookAddin Walkthrough

这是我复制到C# VSTO 2010 Outlook Add-In项目中的演示代码:

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结合发送加密电子邮件后,撤回并编辑邮件消息后重新发送它时,会破坏该消息。当我尝试打开它时,会出现以下错误:
对不起,我们无法打开此项。这可能是暂时的,但如果您再次看到它,则可能需要重新启动Outlook。底层安全系统发生错误。发生内部错误。
我几乎可以确定问题是本地使用的一个或多个对象没有被垃圾回收器自动清理,但我不知道如何强制垃圾回收器(GC)清理它以使其正常工作。我一直在尝试将本地对象设置为null,并找到了一些帖子讨论调用:
GC.Collect();
GC.WaitForPendingFinalizers();

我也一直在尝试解决这个问题,但迄今为止没有成功。有人能提供一些指导如何解决这个问题吗?


也许你需要取消订阅事件订阅?看看这个链接:http://blogs.msdn.com/b/omars/archive/2004/12/07/276136.aspx?Redirected=true - CharithJ
1个回答

3

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

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

但更好的方法是使用System.Runtime.InteropServices.Marshal.ReleaseComObject 在您使用完 Outlook 对象后释放它。如果您的插件尝试枚举存储在 Microsoft Exchange Server 上的集合中的超过 256 个 Outlook 项目,则特别重要。然后在 Visual Basic 中设置变量为 Nothing(在 C# 中为 null),以释放对对象的引用。您可以在 MSDN 中的系统化释放对象文章中阅读更多有关此内容的信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接