C#Outlook 2007 COM互操作应用程序不退出! [英] C# Outlook 2007 COM interop application does not exit!

查看:333
本文介绍了C#Outlook 2007 COM互操作应用程序不退出!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法为什么下列代码不会退出通过COM interop创建的Outlook 2007过程?

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();

使用Word几乎完全相同的代码段,所以我想知道我是否忘记清理一些东西。 ..

An almost identical snippet using Word works, so I wonder if I'm forgetting to clean up something...

推荐答案

您的代码中引用了第三个COM对象: app.Session 。这也必须正确释放。请尝试以下代码:

You have a 3rd COM object referenced in your code: app.Session. This must also be released correctly. Try this code:

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互操作应用程序不退出!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆