devxlogo

Release COM objects earlier

Release COM objects earlier

If you’re using a COM object through COM Interop you should be aware that the object isn’t released as soon as you set it to Nothing, as it happens with VB6. Instead, the object will be released only at the first garbage collections that occurs after the object is set to Nothing or goes out of scope.

If the object’s destructor – the Class_Terminate routine in VB jargoon – contains important code that should be executed as soon as the main application doesn’t need the object any longer – for example, it closes a file or a database connection – you should force the release of the COM object as soon as you don’t need it. You can do this with the Marshal.ReleaseComObject static method. The following examples shows how to do:

' this is a COM component that does cleanup code when it is destroyedDim obj As New MyComLibrary.MyComObject' use the object' ...' force the release of the COM object and set it to NothingSystem.Runtime.InteropServices.Marshal.ReleaseComObject(obj)obj = Nothing

If you aren’t sure that an object variable points to a COM object, you can use the Marshal.IsComObject shared method before using the ReleaseComObject method:

If Marshal.IsComObject(obj) Then    Marshal.ReleaseComObject(obj)End If

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist