为具有COM对象的类编写正确的IDisposable实现 [英] Writing the correct IDisposable implementation for classes with COM objects

查看:195
本文介绍了为具有COM对象的类编写正确的IDisposable实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类使用一个.NET包装器作为COM对象,它给我臭名昭着的RCW错误,所以在我的调查,我发现如果我从这个类的终结器中取出Dispose()方法它会修复RCW错误,所以事情是错误的,例如对象被处置,但注册的事件仍然挂在...但只是删除Dispose()不能是答案,因为谁将释放内存? (我跑了一个内存分析器,并确认只是删除Dispose方法导致像20MB额外的非托管内存)

I have a class that uses a .NET wrapper for a COM object and well it is giving me that infamous RCW error, so in my investigation I found that if I take out the Dispose() method from the finalizer of this class it will fix the RCW error so something is wrong for example the object is getting disposed but the registered events are still hanging around ... But just removing the Dispose() can't be the answer because then who is going to release the memory ? ( I ran a Memory profiler and confirmed that just removing the Dispose method causes like 20MB of extra Unmanaged Memory )

所以应该是错误的,我使用Dispose模型..这里是我有:

so something should be wrong with the way I am using the Dispose model.. here is what I have:

  private MyCOMobject theCOMobject = null;

    static SuppressFieldCntrlr()
    {
        new SomeCalss();
    }

    ~SuppressFieldCntrlr()
    {
       Dispose(false); 
    }



    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                theCOMobject.Dispose();
            }

            MethodFoo(false);

            disposed = true;
        }
    }


推荐答案

COM对象,你需要调用 Marshal.ReleaseComObject 。 Marshal类位于命名空间 System.Runtime.InteropServices 中。

For COM objects, you'll want to call Marshal.ReleaseComObject. The Marshal class is found in the namespace System.Runtime.InteropServices.

更多信息此处

这篇关于为具有COM对象的类编写正确的IDisposable实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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