我使用 C# 创建了一个简单的 Outlook 2007 加载项,该加载项循环选择消息并检查其附件。
我在一组约 25,000 条选定的消息上运行此加载项。然而,我立即注意到 Outlook 的内存使用量(通过 perfmon 看到)猛增。在调试模式下逐行运行加载项后,很明显,在第一次访问邮件的附件集合时,内存已分配给 Outlook。该内存永远不会返回给系统;Outlook 继续消耗内存,直到达到约 1GB(大约 12,000 条消息后),然后我收到“内存或系统资源不足”错误。有任何想法吗?
以下是部分代码:
for(int i = 1; i <= objSelectedItems.Count; i++)
{
Object objMsg = objSelectedItems[i];
//Only process if Item is a Message
if (objMsg is Outlook.MailItem)
{
Outlook.MailItem Msg = objMsg as Outlook.MailItem;
//The culprit: this allocates memory to Outlook which I can't get back
Outlook.Attachments objAttachments = Msg.Attachments;
//Perform some actual work here//
//Clean up Outlook objects; does not appear to give memory back to system
Msg.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
Marshal.ReleaseComObject(objAttachments);
Marshal.ReleaseComObject(Msg);
}
Marshal.ReleaseComObject(objMsg);
GC.Collect();
GC.WaitForPendingFinalizers();
}