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 Program {
static void Main(string[] args) {
var t = new Task(() => DoMemoryHog(20000000));
t.Start();
t.Wait();
t.Dispose();
t = null;
GC.Collect();
Console.WriteLine("Done");
Console.ReadLine();
}
static void DoMemoryHog(int n) {
ConcurrentBag<double> results = new ConcurrentBag<double>();
Parallel.For(0, n, (i) => {
results.Add(Math.Sqrt(i.GetHashCode()));
});
}
}
When I run the program, I can see the amount of used memory increasing in the windows task manager, but when the task is finished (and "Done" is displayed) the memory doesn't go back to it's original level, that only happens when I close the application.
Does anyone know how to free up memory used by a parallel task, while the main application keeps running? As you can see, I've already tried disposing it, setting it's reference to null and running the garbage collector manually (which you shouldn't do, I know).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…