I have a program that does a memory intensive simulation. Below I\'ve written a small console application that replicates the problem I\'m having.
class Prog
I'm sure you don't have a problem with your memory, .NET just doesn't shrink the used Memory so it can be assigend in the future. This saves time for future memory allocation. Try to rerun the loop after it finished, i'm sure the memory wouldn't grow.
So please just try this, i would be intrested in the outcome!
class Program {
static void Main(string[] args) {
Process currentProcess = Process.GetCurrentProcess();
for (int i = 0; i < 10; i++) {
var t = new Task(() => DoMemoryHog(20000000));
t.Start();
t.Wait();
t.Dispose();
t = null;
GC.Collect();
Console.WriteLine("Done" +i);
Console.WriteLine("Memory: " + GC.GetTotalMemory(false));
Console.WriteLine("Paged: " + currentProcess.PagedMemorySize64);
Console.WriteLine("-------------------------");
}
Console.ReadLine();
}
static void DoMemoryHog(int n) {
ConcurrentBag results = new ConcurrentBag();
Parallel.For(0, n, (i) =>
{
results.Add(Math.Sqrt(i.GetHashCode()));
});
}
}
Those two methods are used to print out memory usage:
GC.GetTotalMemory();
currentProcess.PagedMemorySize64;
My output is:
Done0
Memory: 480080992
Paged: 520753152
-------------------------
Done1
Memory: 480081512
Paged: 520753152
-------------------------
Done2
Memory: 480082160
Paged: 520753152
-------------------------
Done3
Memory: 480083476
Paged: 520753152
-------------------------
Done4
Memory: 480083496
Paged: 520753152
-------------------------
Done5
Memory: 480083516
Paged: 520753152
-------------------------
Done6
Memory: 480083536
Paged: 520753152
-------------------------
Done7
Memory: 480084204
Paged: 520753152
-------------------------
Done8
Memory: 480084204
Paged: 520753152
-------------------------
Done9
Memory: 480085500
Paged: 520753152
-------------------------
As far as i can see there is no memory problem here. The objects are cleand up and the memory is reused propery. Issue solved or?
Private bytes behavior:

As you can see the GC is collecting the Objects and freeing the memory, but it's currently not releasing it, so new objects can be allocated.