IDisposable和COM

时间:2010-02-26 20:36:37

标签: .net com idisposable

由于COM对象拥有非内存资源但不支持IDisposable,我正在尝试一些想法来伪造它。你怎么看待我的第一次尝试?

Public Function ComBlock(ByVal ParamArray comObjects As Object()) As IDisposable
    For i As Integer = 0 To comObjects.Length - 1
        If comObjects(i) Is Nothing Then Throw New ArgumentNullException("Null in parameter " & i)
        If Not Marshal.IsComObject(comObjects(i)) Then Throw New ArgumentException(comObjects(i).GetType.Name & " is not a COM object")
    Next

    Return New ComContext(comObjects)
End Function

Private Class ComContext : Implements IDisposable
    Private m_ComObjects As Object()
    Private m_Disposed As Boolean

    Sub New(ByVal comObjects As Object())
        m_ComObjects = comObjects
    End Sub

    Private Sub Dispose() Implements IDisposable.Dispose
        For Each item In m_ComObjects
            Marshal.FinalReleaseComObject(item)
        Next

        GC.SuppressFinalize(Me)
    End Sub

End Class

1 个答案:

答案 0 :(得分:1)

我喜欢你要去的地方。我更倾向于在IDisposable类型中包装我正在使用的COM对象,其中类型公开COM对象的公共成员(想想:适配器)。然后,类中的Dispose()方法将处理COM对象的垃圾收集。

如果使用大量COM对象,则可以从基类继承来处理。我根本没有测试过这段代码,但这通常是我在想的......

public abstract class COMAdapter : IDisposable {

    protected abstract object COMObject { get; }

    public void Dispose() {
        Marshal.FinalReleaseComObject(COMObject);
        GC.SuppressFinalize(this);
    }
}

public class ConcreteAdapter : COMAdapter {
    private YourCOMType _comObject;

    protected override object COMObject {
         get { return _comObject; }
    }
}