在C#中发布COM对象 [英] Release COM Object in C#

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

问题描述

我知道这已经被前面所讨论的,但我无法找到一个满意的答案。

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

我有一个电子邮件文件(。味精),我打开如下图所示,然后调用显示。

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-互操作功能(你是),那么你应该不需要担心这个问题。

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 /调用到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天全站免登陆