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?
}
It’s a managed resource (basically a Runtime Callable Wrapper) and you should clean it up as such. MSDN states that:
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.