Deleting objects using .NET

Note If you use .NET development tools to customize ReadSoft Invoices, garbage collection must be called explicitly when an object is deleted. Simply setting an object to Nothing is not sufficient.

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:

  1. Set all variables referring to an object to Nothing.
  2. 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