How to implement Dispose in a COM object

I wrote a COM component in unmanaged C ++ to give clients access to our database. When used from an unmanaged language, the database connections are cleaned up correctly because the objects are out of scope. I recently tried using it with VB.NET and found that COM objects are not destroyed. Scattering the calls to System.Runtime.InteropServices.Marshal.ReleaseComObject fixes the problem, but I would like to find a simpler and safer solution since this COM object is intended to be used by users.

It seems that the right decision is to managed objects implemented IDisposeable , so you can use the operator using the , automatically calls the Dispose , when the object is no longer needed.

How do I implement an IDisposeable implementation for a subset of my objects? Some objects that require disposal are not co-authored but are returned by other functions.

0


a source to share


2 answers


This is madness. You'd be better off wrapping your COM objects in type-safe .Net wrappers that implement IDisposable (if you like), or use normal .Net garbage collection methods to clean yourself up.



+2


a source


You can go with .NET wrappers, as 1800 INFO suggests, and then remember to always use them with a using statement like you said:

using( var connection = GetDisposableConnection() )
{
    //do stuff
}

      



If that doesn't work because something wasn't released correctly, you can insert these lines on shutdown:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

      

+2


a source







All Articles