连续保存两次相同的邮件时出错



在尝试使用Outlook中MailItemUserProperties添加一些自定义信息时,我发现了一个问题,即邮件无法连续保存两次而不会引发异常

无法执行该操作,因为消息已 改变。

我一直在研究它,有些人建议它可能与未正确释放 COM 对象有关,因此我将代码移动到新的 AddIn,在那里对其进行测试,确保所有对象都已正确发布并且异常仍然存在。这让我认为问题与与IMAP的同步有关,因为我正在使用gmail帐户来测试加载项。但如果是这种情况,我该怎么做才能避免出现此异常?这是我的代码:

注意:该代码旨在在用户每次单击选中邮件的按钮时执行。第一次UserProperty设置为foo和第二次,因为它是相同的 邮件,并且它具有名为custom property的属性,它将值更改为bar. 对同一邮件第二次执行mail.Save()时会引发异常。

Explorer explorer = null;
Selection selection = null;
MailItem mail = null;
UserProperties props = null;
UserProperty prop = null;
try
{
app = Globals.ThisAddIn.Application;
explorer = app.ActiveExplorer();
selection = explorer.Selection;            
mail = selection[1] as MailItem;
string customProperty = "Custom property";
props = mail.UserProperties;
prop = props.Find(customProperty);
if (prop == null)
{
prop = props.Add(customProperty, OlUserPropertyType.olText);
prop.Value = "foo";
Debug.WriteLine("added property: foo");
}
else
{
prop.Value = "bar";                            
Debug.WriteLine("change property: bar");
}
mail.Save();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (prop != null && Marshal.IsComObject(prop))
Marshal.ReleaseComObject(prop);
if (props != null && Marshal.IsComObject(props))
Marshal.ReleaseComObject(props);
if (mail != null && Marshal.IsComObject(mail))
Marshal.ReleaseComObject(mail);
if (selection != null && Marshal.IsComObject(selection))
Marshal.ReleaseComObject(selection);
if (explorer != null && Marshal.IsComObject(explorer))
Marshal.ReleaseComObject(explorer);       
}

我尝试在第二次保存邮件之前等待一段时间,但时间似乎并不重要。有什么建议吗?

注2:当邮件放置在 本地文件夹。

注3:禁用Outlookreading pane,允许我保存 再邮寄一次,第三次引发异常,但保存 如果我第四次尝试,正确

你只在主线程上运行代码吗?是否运行辅助线程?

在代码中,您可以检查属性值及其值。如果该值等于您需要设置的值,则无需分配相同的值。在这种情况下,您可以设置一个标志,表示未对项目执行任何更改,并取消Save调用。

bool skipSave = false;
if (prop == null)
{
prop = props.Add(customProperty, OlUserPropertyType.olText);
prop.Value = "foo";
Debug.WriteLine("added property: foo");
}
else
{
if(prop.Value != "bar")
{
prop.Value = "bar";
Debug.WriteLine("change property: bar");
}
else
skipSave = true;                        
}
if(!skipSave)
mail.Save();

最新更新