// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace E { public class Program { public static void PrintMemoryStatus() { Console.WriteLine("Application has allocated {0} MB from .NET", GC.GetTotalMemory(false)/1000000); Console.WriteLine(".NET has allocated {0} MB from Windows", Process.GetCurrentProcess().PrivateMemorySize64/1000000); } private const int N = 100; public static void Main(string[] args) { PrintMemoryStatus(); Console.WriteLine("Let us allocate {0} MB of managed memory", N); byte[] b = new Byte[N * 1000000]; PrintMemoryStatus(); b[N/2] = 0; // make sure it is not GC'ed before PrintMemoryStatus Console.WriteLine("Let us make it available for GC"); b = null; // never do this in real code GC.Collect(); // never do this in real code PrintMemoryStatus(); Console.WriteLine("Let us allocate {0} MB of unmanaged memory", N); IntPtr buf = Marshal.AllocHGlobal(N * 1000000); PrintMemoryStatus(); Console.WriteLine("Let us make it available for GC"); Marshal.FreeHGlobal(buf); // no point in doing GC for unmanaged memory PrintMemoryStatus(); } } }