Monday, June 16, 2008

Finalizable Types

This variation should be implemented carefully, only after fully considering all the ramifications. Types implementing this variation may cause system starvation if scarce resources are left allocated for longer than needed. In most cases the best coarse of action is to implement the full Disposable and Finalizable (Both) TypesDisposable and Finalizable (Both) Types variation described in section 3.4.
Only types that acquire unmanaged but not scarce resources and zero or more Simple types should implement this variation. For example, a type that allocates only a very small blob of unmanaged memory falls into this category. In such cases having a finalizer ensures that the memory is released but does not oblige clients to call Dispose. This is a rare case and should not be used in most implementations.
Example:
public class FinalizableOnly{
IntPtr nativeMemory = Marshal.AllocHGlobal(4);

~FinalizableOnly(){
Marshal.FreeHGlobal(nativeMemory);
}


}

No comments: