Deleting objects using .NET
This problem is due to the interop mechanism in .NET. Every time a COM interface pointer (for example an InvoiceDefinition object) enters the common language during runtime, it is wrapped in a runtime callable wrapper (RCW). The destruction of this object is handled by the garbage collector and therefore has an indefinite lifetime.
When you access, for example, an InvoiceDefinition property of the Application object in an event handler, a COM object is created that wraps the InvoiceDefinition object. The COM object in turn is wrapped by the RCW object. When the handler returns, the RCW object is not necessarily destroyed. Therefore, references to the COM object and the InvoiceDefinition object are not released, and the database lock is not released since there is still a reference to the invoice definition.
Possible solutions
One solution is to force the RCW to release the COM object by calling ReleaseComObject.
Another alternative is to do this:
- Set all variables referring to an object to Nothing.
- Call Collect() on the GC object before leaving the event handler.
Example:
Public Function OnInvoiceVerify() As Integer
Dim inv As EHICOM.Invoice = comApp.CurrentInvoice
inv = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
Return 0
End Function