隐藏

C#开发获取windows系统CPU使用率高于设置值的进程信息可配置是否显示控制台或隐藏控制台实例

发布:2022/12/17 17:22:10作者:管理员 来源:本站 浏览次数:714

为了解决Windows服务器突发CPU使用率100%,每次想进入系统查看情况又无法远程登录系统,所以为了方便以后能够查看是哪个进程占用CPU高,只有自己写一个控制台程序来记录CPU实时运行情况。

实例:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using System.Configuration;
namespace WinCpu
{
    class Program
    {
        static ILog _log = LogManager.GetLogger("Program");
        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        
        static void Main()
        {
            var _cpu_value = int.Parse(ConfigurationManager.AppSettings["cpu"]);
            var _is_win_show = uint.Parse(ConfigurationManager.AppSettings["is_win_show"]);
            Console.Title = "WAHAHA";
            IntPtr intptr = FindWindow("ConsoleWindowClass", "WAHAHA");
            if (intptr != IntPtr.Zero)
            {
                ShowWindow(intptr, _is_win_show);//隐藏这个窗口
            }
            var counterList = new List<PerformanceCounter>();
            var clist = new List<ProcessInfo>();
            while (true)
            {
                //var procDict = new Dictionary<string, float>();
                var procDict = new List<ProcessInfoModel>();
                Process.GetProcesses().ToList().ForEach(p =>
                {
                    //using (p)
                    //    if (counterList
                    //        .FirstOrDefault(c => c.InstanceName == p.ProcessName) == null)
                    //        counterList.Add(
                    //            new PerformanceCounter("Process", "% Processor Time",
                    //                p.ProcessName, true));

                    using (p)
                    {
                        //var name = string.Empty;
                        //foreach (var instance in new PerformanceCounterCategory("Process").GetInstanceNames())
                        //{
                        //    if (instance.StartsWith(p.ProcessName))
                        //    {
                        //        using (var processId = new PerformanceCounter("Process", "ID Process", instance, true))
                        //        {
                        //            if (p.Id == (int)processId.RawValue)
                        //            {
                        //                name = instance;
                        //                break;
                        //            }
                        //        }
                        //    }
                        //}
                        
                        
                        if (clist.FirstOrDefault(c => c.info.InstanceName == p.ProcessName) == null)
                        {
                            var _name = GetProcessUserName(p.Id);
                            var cpu = new PerformanceCounter("Process", "% Processor Time", p.ProcessName, true);
                            clist.Add(
                                    new ProcessInfo
                                    {
                                        pid = p.Id,
                                        name = _name,
                                        info = cpu
                                    });
                        }
                            
                    }

                });

                clist.ForEach(c =>
                {
                    try
                    {
                        
                        // http://social.technet.microsoft.com/wiki/contents/
                        // articles/12984.understanding-processor-processor-
                        // time-and-process-processor-time.aspx
                        // This value is calculated over the base line of
                        // (No of Logical CPUS * 100), So this is going to be a
                        // calculated over a baseline of more than 100.
                        var percent = c.info.NextValue() / Environment.ProcessorCount;
                        if (percent == 0)
                            return;

                        // Uncomment if you want to filter the "Idle" process
                        //if (c.InstanceName.Trim().ToLower() == "idle")
                        //    return;
                        //procDict[c.info.InstanceName] = percent;
                        procDict.Add(new ProcessInfoModel {
                            pid=c.pid,
                            name= c.name,
                            key = c.info.InstanceName,
                            value= percent

                        });
                    }
                    catch (InvalidOperationException) { /* some will fail */ }
                });
                Console.Clear();
                procDict.OrderByDescending(d => d.value).ToList()
                    .ForEach(d => {
                        Console.WriteLine("{0:00.00}% - {1} - {2} - {3}", d.value, d.key, d.name,d.pid);
                        if(d.value> _cpu_value && d.key!= "Idle")
                        _log.Info(string.Format("{0:00.00}% - {1} - {2}", d.value, d.key,d.name));
                    });
                Thread.Sleep(1000);
            }

        }
        /// <summary>
        /// 获得进程的用户名
        /// </summary>
        /// <param name="pID"></param>
        /// <returns></returns>
        private static string GetProcessUserName(int pID)
        {
            string text1 = null;
            SelectQuery query1 =
                new SelectQuery("Select * from Win32_Process WHERE processID=" + pID);
            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);
            try
            {
                foreach (ManagementObject disk in searcher1.Get())
                {
                    ManagementBaseObject inPar = null;
                    ManagementBaseObject outPar = null;
                    inPar = disk.GetMethodParameters("GetOwner");
                    outPar = disk.InvokeMethod("GetOwner", inPar, null);
                    text1 = outPar["User"].ToString();
                    break;
                }
            }
            catch
            {
                text1 = "SYSTEM";
            }
            return text1;
        }
        public class ProcessInfo {
            public int pid { get; set; }
            public string name { get; set; }
            public PerformanceCounter info { get; set; }
        }
        public class ProcessInfoModel {
            public int pid { get; set; }
            public string name { get; set; }
            public string key { get; set; }
            public float value { get; set; }

        }
    }
}