Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.PrivateMemorySize64 Returns The Same Value Over Multiple Iterations

Tags:

c#

memory

process

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

like image 679
ck. Avatar asked Feb 12 '23 00:02

ck.


1 Answers

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.

like image 161
jordanhill123 Avatar answered Feb 15 '23 11:02

jordanhill123