加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Process.PrivateMemorySize64在多次迭代时返回相同的值

发布时间:2020-12-16 02:03:19 所属栏目:百科 来源:网络整理
导读:此代码在每次迭代中返回相同的值: var process = Process.GetCurrentProcess();for (int i = 0; i 10; i++){ Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);}// Output:// 19853313// 19853313// 19853313// 19853313// ... 此代
此代码在每次迭代中返回相同的值:

var process = Process.GetCurrentProcess();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
}

// Output:
// 19853313
// 19853313
// 19853313
// 19853313
// ...

此代码返回不同的值:

for (int i = 0; i < 10; i++)
{
    var process = Process.GetCurrentProcess();
    Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
}

// Output:
// 19865600
// 20336640
// 20791296
// 21245952
// ...

Process.GetCurrentProcess()是否记录内存值的快照?

MSDN的GetCurrentProcess页面说明了这一点,但我不确定其含义是什么:

获取一个新的Process组件并将其与当前活动的进程相关联

解决方法

您需要调用以下行来刷新它:

process.Refresh();

这应该适合你现在:

var process = Process.GetCurrentProcess();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(process.PrivateMemorySize64 + Environment.NewLine);
    process.Refresh();
}

输出我现在得到:

26152960

26763264

27377664

27922432

28532736

29143040

29757440

30302208

30912512

31522816

从他们提供的例子中的Process.PrivateMemorySize64 Property – MSDN.

此外,从Process.Refresh Method – MSDN开始,这将进一步解释:

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.

有关什么是快照以及什么不是属性方面的一些其他信息,请参阅this StackOverflow Question.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读