To help find your upper limit of memory use, .Net provides the friendly MemoryFailPoint as shown below:
using System;
using System.Runtime;
using System.Text;
namespace PlayingAround {
class Memory {
private static void Main() {
MemoryFailPoint memFailPoint;
StringBuilder sb = new StringBuilder("1234567890");
for (int i = 0; i < 100; i++) {
Console.Out.WriteLine("");
try
{
int aboutToGetMemoryInBytes = sb.Length*5;
Console.Out.WriteLine("aboutToGetMemoryInBytes = " + aboutToGetMemoryInBytes.ToString("#,##0"));
int aboutToGetMemoryInMegaBytes = (int)(1 + (aboutToGetMemoryInBytes >> 20)); //round up to the next megabyte
Console.Out.WriteLine("aboutToGetMemoryInMegaBytes = " + aboutToGetMemoryInMegaBytes.ToString("#,##0"));
using (memFailPoint = new MemoryFailPoint(aboutToGetMemoryInMegaBytes)) {
Console.Out.WriteLine("GC.GetTotalMemory(true) = " + GC.GetTotalMemory(true).ToString("#,##0"));
Console.Out.WriteLine("sb.Length = " + sb.Length.ToString("#,##0"));
//Console.Out.WriteLine(System.Environment.WorkingSet.ToString());
sb.Append(sb.ToString());
}
}
catch (InsufficientMemoryException) {
Console.Out.WriteLine("InsufficientMemoryException.");
var maxMem = GC.GetTotalMemory(true);
Console.Out.WriteLine("maxMem = " + maxMem);
break;
} catch (OutOfMemoryException) {
Console.Out.WriteLine("OutOfMemoryException.");
break;
}
}
Console.Out.Write("press return to exit.");
Console.In.ReadLine();
}
}
}