D
D
Dmitry Gavrilenko2016-07-02 09:37:05
OOP
Dmitry Gavrilenko, 2016-07-02 09:37:05

Dispose pattern from MS?

public class ComplexResourceHolder : IDisposable {

    private IntPtr buffer; // unmanaged memory buffer
    private SafeHandle resource; // disposable handle to a resource

    public ComplexResourceHolder(){
        this.buffer = ... // allocates memory
        this.resource = ... // allocates the resource
    }

    protected virtual void Dispose(bool disposing){
            ReleaseBuffer(buffer); // release unmanaged memory
        if (disposing){ // release other disposable objects
            if (resource!= null) resource.Dispose();
        }
    }

    ~ ComplexResourceHolder(){
        Dispose(false);
    }

    public void Dispose(){
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

What is its meaning if I forget to call Dispose()? The finalizer will work and the resources will not be cleared immediately.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2016-07-02
@none7

If we are talking about a small buffer, then there is really not much sense. But if we are talking about several tens of megabytes of memory, then the OS will start swapping before it starts a full garbage collection. Yes, and this pattern was invented primarily for blocking resources. Such as files, open ports, window handles, threads, and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question