欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 清理内存

程序员文章站 2022-07-03 11:00:28
...

C# 清理内存

介绍

前几天搞了个小玩意,里面有一个清理内存的功能。
它有显示了当前已使用内存的百分比和清理内存的功能。
先上截图。

1.清理之前
C# 清理内存
2.点击之后
C# 清理内存
3.完成!
C# 清理内存

实现方法(分为两部分)

	1.显示内存占用百分比

代码:

	PerformanceCounter cpu = new PerformanceCounter("Memory", "Available MBytes", "");

    float CPU = cpu.NextValue();

    float Be_RAM = (8089 - CPU) / 8089 * 100;

    int over = (int)Be_RAM;

    label1.Text = "内存使用率:" + over + " % ";
	
	// label1.Text是文字控件   然后那个计算式好像是对的吧 我也不知道哇。。。
	
	2.清理内存

这里需要先引用动态链接库 psapi.dll -> pasapi.dll下载地址(如果这个链接挂了的话就去百度吧。。。没办法了)
引用方法:

右键“引用”那两个字。
C# 清理内存
在这里点预览 然后去找你的psapi.dll文件
C# 清理内存

代码:

	[DllImport("psapi.dll")]
    static extern int EmptyWorkingSet(IntPtr hwProc);
    
    public static void ClearMemory()
    {
	    GC.Collect();
	    GC.WaitForPendingFinalizers();
	    Process[] processes = Process.GetProcesses();
	    foreach(Process process in processes)
	    {
		    try
		    {
		    	EmptyWorkingSet(process.Handle);
		    }
		    catch (Exception)
		    {
		    
		    }
	    }
    }
										分-------割-------线	
	如果以上代码有啥问题的话请及时联系我,我看见了就会回复的!!!
相关标签: c#