【问题标题】:'System.InvalidOperationException' occurred in System.dllSystem.dll 中发生“System.InvalidOperationException”
【发布时间】:2016-08-05 19:03:14
【问题描述】:

我正在尝试在控制台应用程序中编写简单的资源监视器。 监视器应显示可用 RAM 内存、已用 RAM 内存、总 RAM 内存、CPU 负载等。

当我尝试运行程序时,我得到了这个异常:

“'System.InvalidOperationException' 类型的未处理异常 发生在 System.dll 中

附加信息:实例 '0,2' 不存在于指定的 类别。”

这是完整的代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace MachineUsage
{
    class Program
    {

        static Double MemoryRAM;
        static PerformanceCounter ramCounter;
        static Int32 CoreCount;

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetWindowPos
            (
            IntPtr hWnd,
            IntPtr hWndInsertAfter,
            int x,
            int y,
            int cx,
            int cy,
            int uFlags
            );

        private const int HWND_TOPMOST = -1;
        private const int SWP_NOMOVE = 0x0002;
        private const int SWP_NOSIZE = 0x0001;

        static PerformanceCounter cpuUsage;

        static void Main(string[] args)
        {
            //Thread CPUthread = new Thread(ResourcesUsage);
            //CPUthread.Start();

            MemoryRAM = getRAM();
            CoreCount = getCoreCount();
            IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;

            SetWindowPos
                (
                hWnd,
                new IntPtr(HWND_TOPMOST),
                0, 0, 0, 0,
                SWP_NOMOVE | SWP_NOSIZE
                );

            var pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            var cat = new PerformanceCounterCategory("Processor Information");

            var instances = cat.GetInstanceNames();
            var cs = new Dictionary<string, CounterSample>();

            Console.WindowHeight = 6;
            Console.WindowWidth = 32;
            Console.Title = "Resources monitor";

            foreach (var s in instances)
            {
                pc.InstanceName = s;
                cs.Add(s, pc.NextSample());
            }

            while (true)
            {
                var s = instances[0];
                pc.InstanceName = s;
                Console.WriteLine("Core count: " + CoreCount + " cores");
                Console.WriteLine("CPU load: " + String.Format("{0:F2}", Calculate(cs[s], pc.NextSample())) + " %");
                Console.WriteLine("Avilable memory: " + getAvailableRAM() + " MB");
                Console.WriteLine("Not avilable memory: " + getNotAvailableRAM() + " MB");
                Console.WriteLine("All memory: " + MemoryRAM + " MB");
                cs[s] = pc.NextSample();
                Thread.Sleep(1000);
                Console.Clear();
            }
        }

        public static Int32 getCoreCount()
        {
            Int32 CoreCount = 0;
            foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                CoreCount += int.Parse(item["NumberOfCores"].ToString());
            }

            return CoreCount;
        }

        public static Double Calculate(CounterSample oldSample, CounterSample newSample)
        {
            double difference = newSample.RawValue - oldSample.RawValue;
            double timeInterval = newSample.TimeStamp100nSec - oldSample.TimeStamp100nSec;
            if (timeInterval != 0 )
            {
                return 100 * (1 - (difference / timeInterval));
            }
            else
            {
                return 0;
            }
        }

        public static Double getRAM()
        {
            UInt64 SizeinKB = Convert.ToUInt64(new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
            UInt64 SizeinMB = SizeinKB / 1024;
            UInt64 SizeinGB = SizeinMB / 1024;
            Double result = Convert.ToInt32(SizeinGB);
            return result;
        }

        public static Double getAvailableRAM()
        {
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            Double result = System.Convert.ToDouble(ramCounter.NextValue());
            return result;
        }

        public static Double getNotAvailableRAM()
        {
            Double result = MemoryRAM - getAvailableRAM();
            return result;
        }

        //public static void ResourcesUsage()
        //{
        //    while(true)
        //    {
        //        cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");

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

        //        Console.Clear();
        //        Console.WriteLine("CPU: "+ cpuUsage.NextValue() + " %");
        //        Console.WriteLine("RAM: " + ramCounter.NextValue() + " MB");
        //        Thread.Sleep(1000);


        //    }
        //}
    }


}

【问题讨论】:

标签: c#


【解决方案1】:

我的 PerformanceCounter (pc) 定义错误。

这是解决方法:

var pc = new PerformanceCounter("Processor Information", "% Processor Time");

我在这里找到了答案: How can I get CPU load per core in C#?

一开始我什至没有检查 PerformanceCounter,然后我复制粘贴了代码并且它起作用了。无论如何,谢谢你们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2017-03-08
    相关资源
    最近更新 更多