知道为什么以下代码不退出通过 COM 互操作创建的 Outlook 2007 进程吗?
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
var item = app.Session.OpenSharedItem("C:\\test.msg") as Microsoft.Office.Interop.Outlook.MailItem;
string body = item.HTMLBody;
int att = item.Attachments.Count;
(item as Microsoft.Office.Interop.Outlook._MailItem).Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
(app as Microsoft.Office.Interop.Outlook._Application).Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
System.Diagnostics.Debugger.Break();
使用 Word 的一段几乎相同的代码片段有效,所以我想知道我是否忘记清理某些东西...
最佳答案
您的代码中引用了第三个 COM 对象:app.Session
。这也必须正确释放。试试这个代码:
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook.NameSpace session = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
try {
app = new Microsoft.Office.Interop.Outlook.Application();
session = app.Session;
item = session.OpenSharedItem("C:\\test.msg") as Microsoft.Office.Interop.Outlook.MailItem;
string body = item.HTMLBody;
int att = item.Attachments.Count;
(item as Microsoft.Office.Interop.Outlook._MailItem).Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
(app as Microsoft.Office.Interop.Outlook._Application).Quit();
} finally {
if(item != null) {
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(item);
}
if(session != null) {
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(session);
}
if(app != null) {
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
}
}
关于C# Outlook 2007 COM 互操作应用程序不退出!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1907270/