简体   繁体   中英

How to reduce the memory usage of my app in C#

I'm building a small program that checks if the resource monitor is open and if so, closes it.

bool a = true;
while (a == true)
{
    foreach (var p in Process.GetProcessesByName("perfmon"))
    {
        Process.Start("taskkill", "/F /IM perfmon.exe");

        // "perfmon" "Taskmgr"
        foreach (var t in Process.GetProcessesByName("taskkill"))
        { 
             ... 
        }
    }
}

The problem is that it takes almost 30% of my CPU performance, so how can I reduce the CPU usage?

Also I tried to add other program like tasklist and task manager but it didn't worked, do you have an idea? :

bool a = true;
            while (a == true)
            {
                System.Threading.Thread.Sleep(1000);
                foreach (var p in Process.GetProcessesByName("Taskmgr"))
                {
                    Process.Start("taskkill", "/F /IM Taskmgr.exe");

                    // "perfmon" "Taskmgr"
                    foreach (var t in Process.GetProcessesByName("taskkill"))

                    {
                        System.Threading.Thread.Sleep(60000);

                        Process b = Process.Start("");
                    }
                }

                foreach (var p1 in Process.GetProcessesByName("perfmon"))
                {
                    foreach (var t1 in Process.GetProcessesByName("taskkill"))

                    {
                        System.Threading.Thread.Sleep(60000);

                        Process b1 = Process.Start("");
                    }

                }

                foreach (var p2 in Process.GetProcessesByName("tasklist"))
                {
                    foreach (var t2 in Process.GetProcessesByName("taskkill"))

                    {
                        System.Threading.Thread.Sleep(60000);

                        Process b2 = Process.Start("");
}
}

Put a Sleep() in your while-loop:

System.Threading.Thread.Sleep(1000);

Your program is constantly checking all processes on your PC. If it does so, only once every second, that's more than enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM