【问题标题】:Process.PrivateMemorySize64 Returns The Same Value Over Multiple IterationsProcess.PrivateMemorySize64 在多次迭代中返回相同的值
【发布时间】:2014-09-18 21:14:33
【问题描述】:

这段代码在每次迭代中返回相同的值:

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 页面这样说,但我不确定这意味着什么:

Gets a new Process component and associates it with the currently active process

【问题讨论】:

    标签: c# memory process


    【解决方案1】:

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

     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,对此有进一步解释:

    在调用 Refresh 后,第一次请求关于每个 属性使流程组件从 相关进程。

    当流程组件与流程资源相关联时, Process 的属性值会立即根据以下内容填充 相关进程的状态。如果有关信息 相关流程随后发生变化,这些变化不会 反映在 Process 组件的缓存值中。 过程 组件是进程资源在它们出现时的快照 联系。要查看关联进程的当前值, 调用 Refresh 方法。

    请参阅this StackOverflow Question,了解有关什么是快照以及什么不是属性方面的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2012-04-22
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2018-08-27
      • 2020-04-10
      相关资源
      最近更新 更多