在 C# 中释放 COM 对象 [英] Release COM Object in C#

查看:34
本文介绍了在 C# 中释放 COM 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前已经讨论过这个问题,但我找不到满意的答案.

I know this has been discussed earlier but I couldn't find a satisfactory answer.

我有一个电子邮件文件 (.msg),我像下面这样打开它,然后调用 Display.

I have an e-mail file (.msg) which I open like below and then call Display.

oApp = new Microsoft.Office.Interop.Outlook.Application();
mail = (Microsoft.Office.Interop.Outlook.MailItem)oApp.Session.OpenSharedItem(fileName);
mail.Display(false);
oApp = null; // do I need to release this object ?

用户可以关闭它并重新打开它.在他们单击重新打开"之前,我会检查窗口是否仍然存在,如果是,那么只需将 SetForeground(hwnd) 发送到该窗口即可.如果不是,那意味着用户关闭了它,所以只需释放 mailItem 对象并再次打开.

users can close it and re-open it. Before they click "reopen" I check to see if the window still exists, if yes .. then just send a SetForeground(hwnd) to that window. if Not, that means user closed it so just release the mailItem object and open again.

 public static void ReleaseCOMObject(Microsoft.Office.Interop.Outlook.MailItem item) {
        int r = System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
        while (r != 0) {
            r = System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
        }
    }

如果我再次尝试打开同一个文件.它有时"会抛出文件正在使用异常"所以,我认为即使我正在发布 MailItem ..它也没有被正确发布.

If I try to open the same file again. It "sometimes" throws a "file in use exception" So, I think even though I am releasing the MailItem .. its not been released properly.

我该怎么做才能确保其正确发布.关闭和重新打开文件是一种非常常见的情况.

What can I do to ensure that its released properly. closing and reopening a file is a very common scenario.

任何指示都会非常有帮助.

Any pointers will be very helpful.

推荐答案

如果您正在使用 .NET 的 COM-interop 功能(您正在使用),那么您无需担心这个问题.

If you're using .NET's COM-interop features (you are) then you shouldn't need to worry about this.

COM 跟踪引用计数——当引用计数达到 0 时,COM 对象会自动释放——并且 .NET 会为您处理标准的 COM 引用计数机制.

COM tracks reference counts - and when the ref count reaches 0 COM objects get released automatically - and .NET takes care of working with the standard COM reference counting mechanism for you.

如果您正在 P/Invoking 到 C 库中,事情可能会有所不同 - 但在像您这样的标准场景中,您不必担心.

If you were P/Invoking into a C library things might be different - but you shouldn't have any worries in a standard scenario like yours.

这篇关于在 C# 中释放 COM 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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