Can't determine memory usage in process
I am trying to ensure that a given block of code does not use excessive memory. I am reading the current used memory with PeakWorkingSet64 () before and after the code block. But the reported value is the same. What's wrong?
private static void memTest()
{
Process p = Process.GetCurrentProcess();
long memBefore = p.PeakWorkingSet64 / 1000;
List<string> l = new List<string>();
int cnt = 0;
try { while (true) { l.Add("Hello World"); cnt++; } }
catch { }
long memAfter = p.PeakWorkingSet64 / 1000;
Console.WriteLine("memBefore={0} memAfter={1} cnt={2}", memBefore, memAfter, cnt);
}
source to share
You must add the following line before getting the PeakWorkingSet64 property again:
p.Refresh();
The reason is described on MSDN:
When a Process component is associated with a process resource, the Process property values ββare immediately populated according to the status of the associated process. If information about the associated process subsequently changes, those changes are not reflected in the cache values ββof the Process component. A process component is a snapshot of a process resource at the time they are linked. To view the current values ββfor the associated process, call the Refresh method.
See this link for details .
source to share