Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dynamic COM objects considered managed resources?

I have a dynamic COM object as a private field in my class. I'm not sure whether it is considered managed resource (GC cleans it up), or not.

private dynamic _comConnector = null;

...

_comConnector = Activator.CreateInstance(Type.GetTypeFromProgID("SomeProgId"));

When implementing IDispose, should I clean it up as a managed resource (only when Dispose() is called explicitly), or as a native resource (when Dispose(false) is called from the finalizer too)?

private void Dispose(bool disposing)
{
    if (disposing)
    {
        // Free managed resources //

        // --> Should I call Marshal.FinalReleaseComObject(_comConnector) here?
    }

    // Free unmanaged resources //

    // --> Or maybe here?
}
like image 205
TX_ Avatar asked Sep 18 '12 07:09

TX_


People also ask

What is dynamic object in C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.

What is the difference between dynamic type variables and object type variables in C#?

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.

Why use dynamic keyword c#?

It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

What is dynamic return type in C#?

C# 4.0 (. NET 4.5) introduced a new type called dynamic that avoids compile-time type checking. A dynamic type escapes type checking at compile-time; instead, it resolves type at run time. A dynamic type variables are defined using the dynamic keyword.


1 Answers

It's a managed resource (basically a Runtime Callable Wrapper) and you should clean it up as such. MSDN states that:

Each RCW maintains a cache of interface pointers on the COM object it wraps and releases its reference on the COM object when the RCW is no longer needed. The runtime performs garbage collection on the RCW.

I.e. the RCW is a managed resource that wraps the unmanaged COM references.

As an aside, releasing COM objects can be dangerous if you are using them from multiple threads in multiple places in your application, as described in this blog post from Chris Brumme.

If you are using a COM object in a scoped, single-threaded manner then you can safely call ReleaseComObject on that object when you are done with it: hopefully this is your case.

like image 97
Joe Avatar answered Dec 03 '22 14:12

Joe