5

最近,我的系统内存不足时遇到了一些问题。花了一段时间才发现发生了什么,但我最终确定,当我将大量数据从文件共享复制到我的机器时,相当大量的内存被放入“待机”。任务管理器似乎没有显示备用内存使用情况,但资源监视器显示。起初我只能通过重新启动来恢复内存,但最终我发现 SysInternals 的人编写了一个很棒的实用程序来释放内存(下面的链接)。

以下是关于备用内存的简要介绍:

备用列表包含已从进程工作集中删除的未修改页面,这有效地使备用列表成为缓存。如果一个进程需要一个在 Standby 列表中的页面,内存管理器会立即将该页面返回到它的工作集。Standby 列表上的所有页面都可用于内存分配请求。如果进程请求内存,内存管理器可以从备用列表中取出一个页面,对其进行初始化,然后将其分配给调用进程。这称为重新调整页面用途。待机列表中的页面通常来自最近使用的文件。通过将这些页面保留在备用列表中,内存管理器减少了从磁盘读取信息的需要。磁盘读取会降低系统响应能力。

(这是来自这里的文档: 内存大小指南

这是该工具的链接: RAMMap

我的问题是:

有谁知道如何以编程方式做到这一点?理想情况下,我想使用 C#,但我将不胜感激任何可能帮助我找到答案的指针。

谢谢!

4

3 回答 3

4

这是我的代码,它是一个控制台应用程序,必须以管理员权限运行。代码是 C#。使用 EmptyWorkingSet 和 MemoryPurgeStandbyList。

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Collections.Generic;

namespace FreeMemory
{
//Declaration of structures
//SYSTEM_CACHE_INFORMATION
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SYSTEM_CACHE_INFORMATION
{
    public uint CurrentSize;
    public uint PeakSize;
    public uint PageFaultCount;
    public uint MinimumWorkingSet;
    public uint MaximumWorkingSet;
    public uint Unused1;
    public uint Unused2;
    public uint Unused3;
    public uint Unused4;
}

//SYSTEM_CACHE_INFORMATION_64_BIT
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SYSTEM_CACHE_INFORMATION_64_BIT
{
    public long CurrentSize;
    public long PeakSize;
    public long PageFaultCount;
    public long MinimumWorkingSet;
    public long MaximumWorkingSet;
    public long Unused1;
    public long Unused2;
    public long Unused3;
    public long Unused4;
}

//TokPriv1Luid
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
    public int Count;
    public long Luid;
    public int Attr;
}
public class Program
{
    //Declaration of constants
    const int SE_PRIVILEGE_ENABLED = 2;
    const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
    const string SE_PROFILE_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
    const int SystemFileCacheInformation = 0x0015;
    const int SystemMemoryListInformation = 0x0050;
    const int MemoryPurgeStandbyList = 4;
    const int MemoryEmptyWorkingSets = 2;

    //Import of DLL's (API) and the necessary functions 
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

    [DllImport("ntdll.dll")]
    public static extern UInt32 NtSetSystemInformation(int InfoClass, IntPtr Info, int Length);

    [DllImport("psapi.dll")]
    static extern int EmptyWorkingSet(IntPtr hwProc);

    //Function to clear working set of all processes
    public static void EmptyWorkingSetFunction()
    {
        //Declaration of variables
        string ProcessName = string.Empty;
        Process[] allProcesses = Process.GetProcesses();
        List<string> successProcesses = new List<string>();
        List<string> failProcesses = new List<string>();

        //Cycle through all processes
        for (int i = 0; i < allProcesses.Length; i++)
        {
            Process p = new Process();
            p = allProcesses[i];
            //Try to empty the working set of the process, if succesfull add to successProcesses, if failed add to failProcesses with error message
            try
            {
                ProcessName = p.ProcessName;
                EmptyWorkingSet(p.Handle);
                successProcesses.Add(ProcessName);
            }
            catch (Exception ex)
            {
                failProcesses.Add(ProcessName + ": " + ex.Message);
            }
        }

        //Print the lists with successful and failed processes
        Console.WriteLine("SUCCESSFULLY CLEARED PROCESSES: " + successProcesses.Count);
        Console.WriteLine("-------------------------------");
        for (int i = 0; i < successProcesses.Count; i++)
        {
            Console.WriteLine(successProcesses[i]);
        }
        Console.WriteLine();

        Console.WriteLine("FAILED CLEARED PROCESSES: " + failProcesses.Count);
        Console.WriteLine("-------------------------------");
        for (int i = 0; i < failProcesses.Count; i++)
        {
            Console.WriteLine(failProcesses[i]);
        }
        Console.WriteLine();
    }

    //Function to check if OS is 64-bit or not, returns boolean
    public static bool Is64BitMode()
    {
        return Marshal.SizeOf(typeof(IntPtr)) == 8;
    }

    //Function used to clear file system cache, returns boolean
    public static void ClearFileSystemCache(bool ClearStandbyCache)
    {
        try
        {
            //Check if privilege can be increased
            if (SetIncreasePrivilege(SE_INCREASE_QUOTA_NAME))
            {
                uint num1;
                int SystemInfoLength;
                GCHandle gcHandle;
                //First check which version is running, then fill structure with cache information. Throw error is cache information cannot be read.
                if (!Is64BitMode())
                {
                    SYSTEM_CACHE_INFORMATION cacheInformation = new SYSTEM_CACHE_INFORMATION();
                    cacheInformation.MinimumWorkingSet = uint.MaxValue;
                    cacheInformation.MaximumWorkingSet = uint.MaxValue;
                    SystemInfoLength = Marshal.SizeOf(cacheInformation);
                    gcHandle = GCHandle.Alloc(cacheInformation, GCHandleType.Pinned);
                    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
                    gcHandle.Free();
                }
                else
                {
                    SYSTEM_CACHE_INFORMATION_64_BIT information64Bit = new SYSTEM_CACHE_INFORMATION_64_BIT();
                    information64Bit.MinimumWorkingSet = -1L;
                    information64Bit.MaximumWorkingSet = -1L;
                    SystemInfoLength = Marshal.SizeOf(information64Bit);
                    gcHandle = GCHandle.Alloc(information64Bit, GCHandleType.Pinned);
                    num1 = NtSetSystemInformation(SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
                    gcHandle.Free();
                }
                if (num1 != 0)
                    throw new Exception("NtSetSystemInformation(SYSTEMCACHEINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
            }

            //If passes paramater is 'true' and the privilege can be increased, then clear standby lists through MemoryPurgeStandbyList
            if (ClearStandbyCache && SetIncreasePrivilege(SE_PROFILE_SINGLE_PROCESS_NAME))
            {
                int SystemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
                GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
                uint num2 = NtSetSystemInformation(SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), SystemInfoLength);
                gcHandle.Free();
                if (num2 != 0)
                    throw new Exception("NtSetSystemInformation(SYSTEMMEMORYLISTINFORMATION) error: ", new Win32Exception(Marshal.GetLastWin32Error()));
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
    }

    //Function to increase Privilege, returns boolean
    private static bool SetIncreasePrivilege(string privilegeName)
    {
        using (WindowsIdentity current = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges))
        {
            TokPriv1Luid newst;
            newst.Count = 1;
            newst.Luid = 0L;
            newst.Attr = SE_PRIVILEGE_ENABLED;

            //Retrieves the LUID used on a specified system to locally represent the specified privilege name
            if (!LookupPrivilegeValue(null, privilegeName, ref newst.Luid))
                throw new Exception("Error in LookupPrivilegeValue: ", new Win32Exception(Marshal.GetLastWin32Error()));

            //Enables or disables privileges in a specified access token
            int num = AdjustTokenPrivileges(current.Token, false, ref newst, 0, IntPtr.Zero, IntPtr.Zero) ? 1 : 0;
            if (num == 0)
                throw new Exception("Error in AdjustTokenPrivileges: ", new Win32Exception(Marshal.GetLastWin32Error()));
            return num != 0;
        }
    }

    //MAIN Program
    static void Main(string[] args)
    {
        //Clear working set of all processes
        EmptyWorkingSetFunction();

        //Clear file system cache
        ClearFileSystemCache(true);

        //Waiting for input of user to close program
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
}
于 2017-01-12T15:02:58.773 回答
2

秘密似乎在 Process Hacker 源代码中(它是用 c 语言编写的)。查看代码,您会看到一个很有希望的命令MemoryPurgeStandbyList,当我们在 GUI 中选择“空待机列表”选项时,它似乎被调用了。

memlists.c(227, 35): command = MemoryPurgeStandbyList;
ntexapi.h(1475, 5): MemoryPurgeStandbyList,

http://processhacker.sourceforge.net/

也可在此处作为命令行版本使用。

于 2013-12-14T16:30:36.507 回答
2

这概述了在 C# 中实现此目标所需的基本步骤

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

public static class MemoryUtility
{
   private static void ClearStandbyCache()
   {
     SetIncreasePrivilege(SE_PROFILE_SINGLE_PROCESS_NAME);

     int iReturn;
     int iSize = Marshal.SizeOf(ClearStandbyPageList);

     GCHandle gch = GCHandle.Alloc(ClearStandbyPageList, GCHandleType.Pinned);
     iReturn = NtSetSystemInformation(SYSTEMMEMORYLISTINFORMATION, gch.AddrOfPinnedObject(), iSize);
     gch.Free();

     if (iReturn != 0)
       Console.WriteLine("Empty Standby List failed");
     else
       Console.WriteLine("Empty Standby List success");
   }



   [DllImport("NTDLL.dll", SetLastError = true)]
   internal static extern int NtSetSystemInformation(int SystemInformationClass, IntPtr SystemInfo, int SystemInfoLength);

   //SystemInformationClass values
   private static int SYSTEMCACHEINFORMATION = 0x15;
   private static int SYSTEMMEMORYLISTINFORMATION = 80;

   //SystemInfo values
   private static int ClearStandbyPageList = 4;

}

此外,这里还有一些文档的链接,其中记录了 SetIncreasePrivilege 方法,并且还包含有关该主题的许多有用资源:http ://www.pinvoke.net/default.aspx/ntdll/NtSetSystemInformation.html

于 2015-09-18T03:59:34.207 回答