c# - 如何正确释放Outlook对象?

标签 c# com outlook mailitem

我无法释放我的 Outlook MailItems。打开 200 封邮件后,Exchange 服务器返回已达到打开的最大邮件数。

我要从所有选定的邮件中删除我的 UserProperty。

我的代码:


foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------


  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}

知道哪里出了问题吗?

最佳答案

你可以试试这个:不是每次都在 For 循环中定义一个新的 MailItem,你可以在 之外定义 mi For 循环或什至在您的类级别,并为每个邮件项目重用它?例如:

MailItem mi;
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {   
   mi= (MailItem)selection;
   // your other code...
 }
 }
mi=null;
GC.Collect();
GC.WaitForPendingFinalizers();

编辑:

尝试为每个引用创建局部变量,例如:

Outlook.Explorer myExplorer=Application.ActiveExplorer(); 
Outlook.Selection mySelection=myexplorer.Selection; 
foreach (var selection in mySelection)
{
}
myExplorer=null;
mySelection=null;
//....

EDIT-2:

如果您使用的是 Outlook 2010,请检查: Outlook 2010 addin selection not clearing

关于c# - 如何正确释放Outlook对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4437447/

相关文章:

c# - 从 Outlook 中获取未读邮件

c# - XNA C# 读取目录内容时出现问题

delphi - 获取 ExcelRange 对象的坐标

c++ - 如何将 CComVariant bstr 转换为 CString

c++ - 使用 iostream 打印 CComBSTR (std::wcout)

vba - 在 Outlook 中发送电子邮件时,如何自动运行宏?

vb.net - 无法访问 Outlook 2010 VB.Net 中的共享联系人文件夹

c# - 如何检查文件是否存在c#

c# - 混合不同数据源的存储库实现

c# - 如何在 visual studio 2010 C# 中获取字符串的堆栈内存地址