This code returns the same value in every iteration:
var process = Process.GetCurrentProcess();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
}
// Output:
// 19853313
// 19853313
// 19853313
// 19853313
// ...
This code returns different values:
for (int i = 0; i < 10; i++)
{
var process = Process.GetCurrentProcess();
Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
}
// Output:
// 19865600
// 20336640
// 20791296
// 21245952
// ...
Does Process.GetCurrentProcess() take a snapshot of memory values?
MSDN's GetCurrentProcess page says this, but I'm not sure what the implications are:
Gets a new Process component and associates it with the currently active process
You need to call the following line in order to refresh this:
process.Refresh();
This should work for you now then:
var process = Process.GetCurrentProcess();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
process.Refresh();
}
Output I'm now getting:
26152960
26763264
27377664
27922432
28532736
29143040
29757440
30302208
30912512
31522816
From Process.PrivateMemorySize64 Property - MSDN in their supplied example.
In addition, from Process.Refresh Method - MSDN, this is explained further:
After Refresh is called, the first request for information about each property causes the process component to obtain a new value from the associated process.
When a Process component is associated with a process resource, the property values of the Process are immediately populated according to the status of the associated process. If the information about the associated process subsequently changes, those changes are not reflected in the Process component's cached values. The Process component is a snapshot of the process resource at the time they are associated. To view the current values for the associated process, call the Refresh method.
See this StackOverflow Question for some additional information around what is a snapshot and what is not in terms of properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With