get current CPU utilization in C#

前端 未结 2 1327
北荒
北荒 2021-02-08 04:36

I want to have current CPU utilization in my project

namespace Monitoring_Tool
{
    public partial class ajaxExecute : System.Web.UI.Page
    {
        private          


        
2条回答
  •  名媛妹妹
    2021-02-08 05:32

    That's because you need to call NextValue multiple times on the same PerformanceCounter instance (so at least twice). The first call will always return 0.

    You can work around this (sort of) by calling NextValue twice in your Page_Load event handler, only storing the return value of the second call:

            float cpuUsage = 0.00F;
    
            this.theCPUCounter.NextValue();
            cpuUsage = this.theCPUCounter.NextValue();
    

    The reason it shows in the QuickWatch of the debugger is probably just because it is (implicitly) called multiple times (once by the program and once by the debugger for the QuickWatch value).

    Update to the "sort of" above:

    As others have mentioned you usually need to sleep some time between the two calls to actually observe a difference in CPU load that results in a "measurable" difference. Sleeping for 1 s usually does the trick, but might not be an acceptable delay in the loading of your page.

    What you really want to do is provide a background thread that repeatedly queries this performance counter, sleeping a couple of seconds in between. And storing the result somewhere. From your Page_Load or other events / functions query the (last) value. All with necessary locking against data races of course. It will be as accurate as you can get with regards to this pointer.

    Since you are obviously using ASP.NET you have to be careful with such background threads. I'm no ASP.NET expert, but according to this it should be possible, even though the thread (and the perf counter readings it did) will be recycled, when your app domain / web application is. However, for this kind of functionality that shouldn't be an issue.

提交回复
热议问题