分配内存c#

  static void AllocBigMemoryBlock (int pass)
        {
            const int MB = 1024 * 1024;
            byte[] array = null;
            long maxmem = 0;
            int arraySize = 0;

            GC.Collect ();
            GC.WaitForPendingFinalizers ();
            while (true)
            {
                try
                {
                    arraySize += 10;
                    array = new byte[arraySize * MB];
                    array[arraySize * MB - 1] = 100;
                    GC.Collect ();
                    GC.WaitForPendingFinalizers ();
                    maxmem = GC.GetTotalMemory (true);
                    Console.Write ("Pass: {0}     Array Size (MB): {1:D4}  {2:D4}/r", pass, arraySize, Convert.ToInt32 (maxmem / MB));
                }
                catch (System.OutOfMemoryException)
                {
                    GC.Collect ();
                    GC.WaitForPendingFinalizers ();
                    maxmem = GC.GetTotalMemory (true);
                    Console.Write ("/n");
                    Console.Write ("Pass: {0} Max Array Size (MB): {1:D4}  {2:D4} {3}/r/n/n", pass, arraySize, Convert.ToInt32 (maxmem / MB), "System Out of Memory...");
                    break;
                }
                finally
                {
                    array = null;
                    GC.Collect ();
                    GC.WaitForPendingFinalizers ();
                }
            }
        } 

你可能感兴趣的:(分配内存c#)