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?
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With