0

I have written a COM component in unmanaged C++ to provide customers access to our database. When using it from an unmanaged language the database connections are correctly cleaned up as the objects go out of scope. I recently tried using it from VB.NET and discovered that the COM objects are not being destroyed. Scattering calls to System.Runtime.InteropServices.Marshal.ReleaseComObject fixes the problem, but I'd like to find a simpler and exception safe solution since this COM object is designed for customer use.

It appears that the correct solution is to have the managed objects implement IDisposeable so the using statement can be used, automatically calling Dispose when the object is not longer required.

How do I go about implementing IDisposeable for a subset of my objects? Several of the objects that require disposing are not co-creatable but are returned by other functions.

1

2 Answers 2

2

Madness lies that way. You'll be better off wrapping your COM objects in type safe .Net wrappers that implement IDisposable (if you like), or use the normal methods of .Net garbage collection to clean themselves up.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a better way to ensure the database connections are closed other than to use IDisposable? I'd really like to ensure that all the COM objects are cleaned up as currently there is a crash on exit when my caches in the COM component are destroyed in DllMain. If the COM objects were released the caches would be empty.
2

You could go with the .NET wrappers as 1800 INFORMATION suggests, then remember to always use them with a using statement as you said:

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

If this doesn't work because something wasn't being released correctly, you can insert these lines when shutting down:

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

2 Comments

Thanks for the tip of calling WaitForPendingFinalizers, I had not come across that before.
No problem - glad to have helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.