C# Outlook 2007 COM 互操作应用程序不退出!
知道为什么以下代码不退出通过 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 可以得到几乎相同的片段,所以我想知道我是否忘记清理一些东西......
Any ideas why the following code does not exit the Outlook 2007 process created via COM interop?
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();
An almost identical snippet using Word works, so I wonder if I'm forgetting to clean up something...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码中引用了第三个 COM 对象:
app.Session
。这也必须正确释放。试试这个代码:You have a 3rd COM object referenced in your code:
app.Session
. This must also be released correctly. Try this code:我不知道 Office COM Interops 的具体细节,但这里有一些来自 MSDN 文章。它表明双重收集/等待和清除指针有助于 RCW 包装器清理。
然而,该网址也表明,
如果您可以帮助的话,我个人强烈建议您不要这样做,因为您基本上刚刚销毁了您的 AppDomain 的 RCW(正如文章所指出的)。
[编辑:此外,.Net 垃圾收集器在调试器内部与发布代码中的行为非常不同,因此在调试器外部进行测试非常重要]
I don't know the specifics of the Office COM Interops, but here's some code suggested from an MSDN article. It suggests the double collect/wait and clearing of the pointers helps with the RCW wrapper cleanup.
That url however also suggests
which I would personally strongly advise against if you can help it, as you've basically just destroyed that RCW for your AppDomain (as the article points out).
[Edit: Also the .Net garbage collector behaves very differently when inside a debugger vs release code, so testing this outside of the debugger is very important]
试试这个,它对我有用,在它消失之前会有几秒钟的延迟:
Try this instead, it works for me, there will be a few second delay before it goes:
在 app.Quit(); 之后尝试以下操作
Try following after app.Quit();