menu 纱雾の抱枕
调用 Windows 底层的 Psapi 清理进程工作集实现清理内存
16 浏览 | 2021-05-02 | 阅读时间: 约 1 分钟 | 分类: 计算机 | 标签: C#,工具,笔记

起因

闲来无事~

C# 实现

// Api access class .
static class Api
{
        // Import from the dll .
        [DllImport("psapi.dll", EntryPoint = "EmptyWorkingSet")]
        // Empty by the process handle .
        public static extern bool Empty(IntPtr hProcess);

        // Clean up through the Process instance .
        public static bool Empty(Process ProcessInstance, bool Output = true)
        {
            // Try to clean up the memory of this process .
            try
            {
                // Determine whether the cleanup is successful .
                if (Empty(ProcessInstance.Handle))
                {
                    // Determine whether to open the command line output .
                    if (Output)
                    {
                        // Set the console font color to green .
                        Console.ForegroundColor = ConsoleColor.Green;
                        // Output completion information to the command line .
                        Console.WriteLine("[Info] Successfully cleaned the memory for " + ProcessInstance.ProcessName + "#" + ProcessInstance.Id.ToString() + " !");
                        // Set the console font color to white .
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    // Return true .
                    return true;
                }
                else
                {
                    // Set the console font color to yellow .
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    // Determine whether to open the command line output .
                    if (Output)
                    {
                        // Output error to the command line .
                        // Example : "[Error]Failed to clean up memory for System#4 !"
                        Console.WriteLine("[Error] Failed to clean up memory for " + ProcessInstance.ProcessName + "#" + ProcessInstance.Id.ToString() + " !");
                    }
                    // Set the console font color to white .
                    Console.ForegroundColor = ConsoleColor.White;
                    // If unsuccessful , return false .
                    return false;
                };
            }
            // Capture the error of the program .
            catch (Exception Ex)
            {
                // Set the console font color to yellow .
                Console.ForegroundColor = ConsoleColor.Yellow;
                // Determine whether to open the command line output .
                if (Output)
                {
                    // Output error to the command line .
                    // Example : "[Error]Fatal call error occurred while cleaning memory for System#4 !"
                    Console.WriteLine("[Error] Fatal call error occurred while cleaning memory for " + ProcessInstance.ProcessName + "#" + ProcessInstance.Id.ToString() + " !");
                    Console.WriteLine(Ex.ToString());
                }
                // Set the console font color to white .
                Console.ForegroundColor = ConsoleColor.White;
                // If unsuccessful , return false .
                return false;
            }
        }

        // Empty by the process array . ( Maybe more than one process )
        public static bool Empty(Process[] ProcessesArray, bool Output = true)
        {
            // Create result variables in advance .
            var Result = true;
            // Traverse the process .
            foreach (Process Item in ProcessesArray)
            {
                // Clean up through the Process instance .
                if (!Empty(Item, Output))
                {
                    // If unsuccessful , return false .
                    Result = false;
                }
            }
            // Return the execution result failed or succeeded .
            return Result;
        }

        // Empty by the process name . ( Maybe more than one process )
        public static bool Empty(string Name, bool Output = true)
        {
            // Empty by the process array .
            return Empty(Process.GetProcessesByName(Name), Output);
        }

        // Empty by the process id .
        public static bool Empty(int Pid, bool Output = true)
        {
            // Clean up through the Process instance .
            return Empty(Process.GetProcessById(Pid), Output);
        }

        // Clean up all processes .
        public static bool Empty(bool Output = true)
        {
            // Clean up through the Process instance .
            return Empty(Process.GetProcesses(), Output);
        }
}

调用

直接 Api.Empty(参数); 即可。如果留空,就是清理所有存在的进程。如果是数字,那就是作为 Pid 来获取进程句柄并且清理它的工作集。如果是字符串,那就作为进程名来搜索进程并且清理,这里可能会清理多个进程,所以上面用了遍历方式逐个清理。如果是 IntPtr 指针类型,那么就是作为 ProcessHandle 对其清理。如果是 Process[] Array 那么就遍历并清理。如果要关闭控制台输出,那么就在函数后面加上结尾参数 false 关闭控制台输出!

应用

在我的 GitHub 上有个项目 Noel Gc ,里面注释很清楚,是命令行工具,具体跳到 GitHub 看!

原理

调用 Psapi.dll 内的 EmptyWorkingSet 函数,参数是 hProcess ,也就是进程句柄。可以参阅微软的文档

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

发表评论

email
web

全部评论 (暂无评论)

info 还没有任何评论,你来说两句呐!