我无法释放我的 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/