首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连续监视线程的CPU使用情况

连续监视线程的CPU使用情况
EN

Stack Overflow用户
提问于 2017-02-16 10:20:11
回答 1查看 404关注 0票数 0

我需要一个线程在Windows服务,它不断监测CPU的使用(也许每5秒)。如果CPU使用率较低,则应激活其他线程。

我已经从这个SO Question中找到了一个示例CPU使用监控代码(我在下面的文章中也给出了)。这是控制台应用程序的代码,为了保持Timer正常运行,用户在最后使用Console.ReadLine();

CPU使用控制台应用程序:

代码语言:javascript
复制
using System;
using System.Diagnostics;
using System.Timers;
using System.Threading;
using System.Collections.Generic;

namespace CPUPerformanceMonitor
{
    class MonitoringApplication
    {
        protected static PerformanceCounter cpuCounter;
        protected static PerformanceCounter ramCounter;

        public static void TimerElapsed(object source, ElapsedEventArgs e)
        {
            float cpu = cpuCounter.NextValue();
            float ram = ramCounter.NextValue();
            Console.WriteLine(string.Format("CPU Value: {0}, ram value: {1}", cpu, ram));
        }

        public static void Main()
        {
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

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

            try
            {
                System.Timers.Timer t = new System.Timers.Timer(1200);
                t.Elapsed += new ElapsedEventHandler(TimerElapsed);
                t.Start();
                Thread.Sleep(10000);
            }
            catch (Exception e)
            {
                Console.WriteLine("catched exception");
            }

            while (true) //Another sample BAD way to keep the timer alive
            { }

            //Console.ReadLine(); //just to keep the time alive
        }
    }
}

问题:如何在Windows应用程序中实现它.我是说,我怎样才能维持这条线。

My Windows-服务结构:

我调用线程回调方法OnStart()。这个线程回调方法调用类CPUMonitorCPUMonitor方法(它包含Timer的代码)。

代码语言:javascript
复制
    public void CPUMonitorinigThreadCallback()
    {
        //If nothing is there in this function, the thread will start up and then immediately shutdown. To deal with this situation, use "_shutdownEvent"
        //The while loop checks the ManualResetEvent to see if it is "set" or not.
        while (!_shutdownEvent.WaitOne(0))
        {
            // Replace the Sleep() call with the work you need to do
            //Sleep(1000);
            objCPUMonitor.StartCPUMonitorinig();
        }

    }
EN

回答 1

Stack Overflow用户

发布于 2017-02-16 11:34:36

要将其实现为Service类型,您必须考虑输出性能数据的位置和方式。使用Windows,我可以建议创建另一个应用程序或覆盖,然后在Service结束更新时显示这些值。这可以使用共享内存、文件、数据库、windows消息泵、std out等来完成。

考虑到这些因素,您实际上可以通过创建一个service对象来开始您的服务:

代码语言:javascript
复制
public class MeService : ServiceBase
{
    // for the ability to redirect stream
    [DllImport("Kernel32.dll", SetLastError = true) ]
    public static extern int SetStdHandle(int device, IntPtr handle); 

    // entry point
    public static void Main(string[] args)
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new MeService()
        };
        ServiceBase.Run(ServicesToRun);
    }

    PerformanceObject pObject; // object to retrieve and return performance status
    IContainer components;
    FileStream fStream;
    public MeService()
        : base()
    {
        components = new Container(); // initialize components holder
        ServiceName = "MeService"; // set your service name
    }

    // Here check for custom commands on your service
    protected override void OnCustomCommand(int command)
    {
        if(command == 1)
        {
            // redirect stream
            fStream = new FileStream("<path_to_your_out_file>", <FileMode.Here>, <FileAccess.Here>);
            IntPtr streamHandle = fStream.Handle;
            SetStdHandle(-11, handle); // DWORD -11  == STD OUT
        }
        else if(command == 1337 && pObject != null) // example command
        {
            // write string.Format("CPU Value: {0}, ram value: {1}", cpu, ram);
            // into your service's std out
            Console.WriteLine(pObject.GetPerformance()); 
        }
        base.OnCustomCommand(command);
    }

    // whenever service starts create a fresh performance counter object
    protected override void OnStart(string[] args) // will be called when service starts
    {
        pObject = new PerformanceObject();
    }

    // called whenever service is stopped
    protected override void OnStop()
    {
        // remove performance counter object 
        pObject.Dispose();
        pObject = null;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }

            if (pObject != null)
            {
                pObject.Dispose();
            }
        }
        base.Dispose(disposing);
    }
}

现在,在完成这些操作之后,您可以创建“显示”应用程序。这应该将服务的std重定向到它自己的读取器,使您能够从该流中读取。

代码语言:javascript
复制
class Program
{
    static void Main(string[] args)
    {
        FileStream fileStream = new FileStream("<PATH_TO_THE_SAME_FILE_AS_SERVICE>", <FileMode.Here>, <FileAccess.Here>);
        // create service controller that will control "MeService" service
        ServiceController Controller = new ServiceController("MeService");
        if (Controller.Status == ServiceControllerStatus.Stopped)
        {
            Controller.Start();
        }

        while (Controller.Status != ServiceControllerStatus.Running)
        ;

        Controller.ExecuteCommand(1); // redirect the stream.           

        string command = string.Empty;
        while( ( command = Console.ReadLine() ) != "exit" )
        {
            if(command == "refresh")
            {
                if (Controller.Status == ServiceControllerStatus.Running)
                {
                    Controller.ExecuteCommand(1337);
                    string performance = fileStream.ReadLine();
                    Console.WriteLine(performance);
                } 
            }
        }
    }
}

现在,您所要做的就是在服务中创建一个安装文件,并创建您已经拥有的PerformanceObject,但是您必须修改它,以便在上面的代码段中使用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42271024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档