Friday, July 15, 2016

dispose pattern

Note: user called dispose() and gc both clean up unmanaged resources. gc does not clean up managed resources as it cleans up objects in any order.

basic dispose pattern
// basic dispose pattern
// only managed resources
basicdispose: idisposable
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources

dispose pattern for finalizable type
Note: there is a performance penalty with finalize types as they go through the finalize and f-reachable queues.
// dispose pattern for finalizable type
// managed and unmanaged resources
// finalizable types are put in finalize and f-reachable queues by gc
finalizable: idisposable
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources
        // clean unmanaged resources
    
    // finalize(), gc calls
    ~finalizable():
        dispose(false)

basic dispose pattern with inheritance
With inheritance, call the base class dispose(bool) as well.
basicdispose: idisposable
    // ...

basicdisposeChild: basicdispose
    // user calls
    dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources
        // clean unmanaged resources
        disposed = true
        
        // call base class dispose(bool)
        base.dispose(disposing)

With disposed flag
basicdispose: idisposable
    disposed = false
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposed:
            return
        if disposing:
            // clean managed resources
        disposed = true

No comments:

Post a Comment