专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

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

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:14:12       共计:3621 浏览

为了解决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; }

        }
    }
}

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:使用CSS矢量图标Font Awesome | ·下一条:在C#中的PerformanceCounter类的使用实例

Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有