[英]C# Outlook 2007 COM interop application does not exit!
任何想法為什么以下代碼不退出通過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);
}
}
我不知道Office COM Interops的具體細節,但這里有一些MSDN文章中提出的代碼。 它建議雙重收集/等待和清除指針有助於RCW包裝器清理。
item = null;
app.Quit();
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
然而,該網址也表明了這一點
while (Marshal.ReleaseComObject(app) > 0) { }
如果你能提供幫助,我個人會強烈反對,因為你基本上只是為你的AppDomain銷毀了RCW(正如文章指出的那樣)。
[編輯:在調試器和發布代碼中,.Net垃圾收集器的行為也非常不同,因此在調試器外部進行測試非常重要]
在app.Quit()之后嘗試關注;
// ReleaseComObject(xApp);
GC.WaitForPendingFinalizers();
GC.Collect();
試試這個,它適用於我,它會有幾秒鍾的延遲:
app.Quit(); //
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
GC.WaitForPendingFinalizers();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.