C# and Resource Management: Best Practices for Handling Unmanaged Resources

1 Minute(s) to read

C# is commonly used on Windows with the Common-Language Runtime which is provided by the .NET Framework, an execution environment and interpreter that executes, and translates code from JIT-compiled IL instructions to native assembly instructions. The Common-Language Run-time additionally handles memory management for heap and stack allocations, and garbage collection where possible, however there are still instances where memory leaks can occur.

Resource streams and file handles can be allocated and opened and left in such state for the entire duration of an application's lifetime unless they are explicitly disposed of. This is regardless of whether or not the GC has highlighted a GC root (e.g. reference to heap allocated memory) as being suitable for deletion. This blog post intends on describing the best methods of leveraging the GC routines (i.e. finalizers), and C# programming conventions for ensuring that resources allocated properly disposed of.

Finalizer

For the sake of simplicity, the "finalizer" could be considered synonymous with the destructor in C++, with the caveat that it cannot be explicitly invoked. It is a routine or function that is invoked when an object is being destroyed and subsequently deallocated or freed from memory. When defined in a C# class, the garbage collector during a collection routine will invoke the 

IDisposable

 

Example

    /// <summary>
    ///     
    /// </summary>
    public interface IFinalizable : IDisposable
    {
        /// <summary>
        ///     
        /// </summary>
        /// <param name="disposing"></param>
        void Dispose(bool disposing);

        /// <summary>
        ///     
        /// </summary>
        bool IsDisposed { get; }
    }

Resources



Comments