Home » VB.Net

How do I get CPU usage from WMI?

Hi people,

I started using WMI to get Drive, Memory, and CPU information. But I am not sure or don't know how to get CPU usage. This is part of a system monitoring functionality I am trying to implement. I need CPU's usage like the same as you get from Task Manager(in percentage). I don't need CPU's temperature.

Also, I need total memory(as in RAM). This is the same RAM from My Computer >> Properties. Example: 2.99GB of RAM. I got FreePhysicalMemeory and FreeVirtualMemeory from Win32_OperatingSystem but I still need the total RAM. I am thinking FreeVirtualMemory is from HardDrive and FreePhysicalMemory is from the RAM that is not being used, and thus free for use.



15 Answers Found


Answer 2

Just a small addtion to the previous great link:

Computer Memory you can get from Win32_ComputerSystem -> TotalPhysicalMemory
CPU counter you can get from Win32_PerfFormattedData_Counters_ProcessorInformation -> PercentProcessorTime; the first collection entry returns total  for all processors and cores, the 2nd entry all cores of the first processor. If the system  has just one processor they are the same


Answer 3

Something simple like this will work.

Forward Declarions:

	private: System::Management::SelectQuery^ Info
	private: System::Management::ManagementObjectSearcher^ Searcher;
 private: int cpuUsage (System::Object^ sender, System::EventArgs^ e)
this->Info = gcnew System::Management::SelectQuery("Win32_PerfFormattedData_PerfOS_Processor ");
this->Searcher = gcnew System::Management::ManagementObjectSearcher(Info);
Object^ idleTime;
ManagementObject^ envVar;
for each (envVar in Searcher->Get()) { idleTime = envVar["PercentIdleTime"]; } return 100 - int::Parse(idleTime->ToString()); }

Answer 4

Hi UgnV,

This looks good but can you get me code in VB? if possible?

I can try the Win32_ComputerSystem -> TotalPhysicalMemory first. I assume this will give me the total  RAM; the same RAM as you get from My Computer -> Properties? But how do I get total free  RAM?

I will need some code to get the percentage  of CPU's usage  from Win32_PerfFormattedData_Counters_ProcessorInformation -> PercentProcessorTime.



Answer 5

Thanks for replying pyrox,

I am not sure how to implement  your code. I assume its in c++ and I don't see the return value that I needed. I need total  RAM and total free  RAM.

And I also need CPU's usage  in percentage.



Answer 6

Download the WMI Creator!!

It generates code in several languages.


Answer 7

Hi Tergiver,

I downloaded and ran the creator. There's 472 classes. How the heck do I know which one to run? Besides the classes mentioned above?

As of now, I got the total  RAM. I still need the CPU's usage  in percentage.



Answer 8

Hi Tergiver,

The Creator have no: 


under: root\CIMV2

Anyway, I got an error from the following when I tried to grab CPU's usage  from below:

Dim scope5 = New ManagementScope()
    Dim queryBuilder5 = New StringBuilder()

    queryBuilder5.Append("SELECT PercentProcessorTime FROM Win32_PerfFormattedData_Counters_ProcessorInformation")

    Dim query5 = New ObjectQuery(queryBuilder5.ToString())
    Dim search5 = New ManagementObjectSearcher(scope5, query5)

    Dim collectionOfResults5 As ManagementObjectCollection

    collectionOfResults5 = search5.Get()

    Dim currentObject5 As ManagementObject

    'Display Total RAM information
    For Each currentObject5 In collectionOfResults5
      '_collected.AddFirst("CPU's Usage(%): " + currentObject5("PercentProcessorTime").ToString()))
      lbDiskInformation.Items.Add("CPU's Usage(%): " + currentObject5("PercentProcessorTime").ToString())

I got an error at the end(at the For Each loop). The collectionOfResults5 yield nothing.




Answer 9

Hi BlueMarker,

To get free memory  you can use Win32_PerfFormattedData_PerfOS_Memory ->AvailableBytes or AvailableMBytes
Below is the working code in VB that gets CPU percentage  sample and free  memory

Imports System
Imports System.Management
'Imports System.Windows.Forms

Module Module1

  Sub Main()


  End Sub

End Module

Namespace WMISample

  Public Class MyWMIQuery

    Public Overloads Shared Function Main() As Integer

      Dim processorSearcher As New ManagementObjectSearcher( _
       "root\CIMV2", _
       "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation")

      For Each queryObj As ManagementObject In processorSearcher.Get()

        Console.WriteLine("PercentProcessorTime: {0}", queryObj("PercentProcessorTime"))

        ' for system  with single processor we exit after the 1st iteration
        Exit For

      Dim memorySearcher As New ManagementObjectSearcher( _
        "root\CIMV2", _
        "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory")

      For Each queryObj As ManagementObject In memorySearcher.Get()
        Console.WriteLine("AvailableBytes: {0}", queryObj("AvailableBytes"))
        Console.WriteLine("AvailableMBytes: {0}", queryObj("AvailableMBytes"))

    End Function
  End Class
End Namespace

Best Regards,


Answer 10

Thanks for the help.

Ugnv pointed to the appropiate class and code which help me.

Tergives pointed me the the WMI Creator which is helpful but I still need to know which class and which value to select.

I will mark both as answer.

Thanks again,



Answer 11

There's 472 classes. How the heck do I know which one to run?

I know you're going to hate this answer, but I love giving it:



Answer 12

There's 472 classes. How the heck do I know which one to run?
That is called connecting the dots.  Get used  to it.  ;)

Answer 13

Already got this saved in My Favorites...

I was on my way to the answer...just need the needle in the hay stack :)



Answer 14

Yea, this could be fun. Problem is: I got a little deadline. Learn something new everyday....that's for sure.

Answer 15

Already got this saved in My Favorites...

I was on my way to the answer...just need the needle in the hay stack :)


Save a link in your code inside of a comment.

// links

// http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/608a2bc0-3bf8-4845-b0d8-09f2624189f7#bb899507-8c45-478a-b484-3e381b933d22



I have run into a particular setup where the CPU information provided by WMI is incorrect. This is consistent across all similar setups and not isolated to a particular instance.

CPU: Intel Xeon CPU E54xx series
OS: Win2K3

The CPU name provided by WMI is "Intel(R) Pentium(R) III Xeon processor"
The value in the registry is accurate though.

I am in the process of verifying if this is the case with Win2K or other OS also.

Can someone shed some light on why this happens and what can be done to rectify this?



I've been through a number of posts dealing with WMI and its ability to report CPU temperature.  I have to say that I'm more confused now than ever. 

Could someone please let me know if WMI is a way to go assuming that I'll be dealing with XP and/or Windows 7 and running on most recent motherboards?

If WMI is not a good option then what are the better options?




   Is there some way of retrieving a value for the level of cpu usage for any given time in wpf? thanks


Hi Folks;

We only recently employed SQLDependency for a project at work. We are using it to invalidate and refresh cache with the most up-to-date lookup data. Performance testing has revealed that the cpu/memory usage on our database server is such:

Without SQLDependency and broker disabled in the DB:

CPU = ~5-10%

Memory = ~1GB

With SQLDependency and broker enabled in the DB:

CPU = ~10-15%

Memory = ~1.5GB

However in the later case, we see that memory usage grows with time till SQL Server uses almost all of the allocated memory.

My questions are:
Are there any known issues with SQLDependency and broker service that would explain this sort of increased CPU/Memory usage? What are the known levels of CPU/Memory increase with using SQLDependency and broker service? 

We are using 64-bit SQL Server 2005 with SP3 and the server instance is configured to use a minimum of 512MB RAM and a maximum of 6GB. It is installed on a dedicated 64-bit DB server running Windows Server 2003.

Thanks in advance.

I have developed Windows app in C# with DirectX and I see in a CPU Usage almost 100% whenever any other appilcation window overlaps my application. I mean my application is running in background windows which is not active at the moment. The other active application is ovelapping it and CPU usage raising its bar to 100%.

Could you please help me, how I can solve this problem?

Hello everyone,

First, Sorry for my poor English.

Currently I'm trying to write a program about network communication.

When I compiled my program with "CL server.cpp ws2_32.lib" then run server.exe,

the process of Windows Defender eats a whole core of my CPU for 20 seconds when my program runs.

I have tried another 2 compiler, this doesn't happen with VC2008 or MinGW-GCC4.5

 ( 2008 is also causes defender eats a whole core but not for that long. just about 1 second )

At last I compiled with "CL server.cpp ws2_32.lib /Zi" (VC2010) and run server.exe, it eats a whole core of my CPU for 2 seconds only. but it's still too long and I don't need debug information.

Could someone give me a solution to solve the problem that my program compiled with VC2010 causes Windows Defender eat too much CPU? thanks



Windows 7 Professional OEM

Visual C++ 2010 Express

Visual C++ 2008 Express


Avast! Free Edition and Comodo Firewall (with Defense+ off) is running in background


here is the code

#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <setjmp.h>

char buf[65535];
jmp_buf jb;




enum { PORT = 10801 };

int checkDest(SOCKADDR_IN *sa) {
  if(sa->sin_addr.s_addr & 0xff == 10) return -1;
  if(sa->sin_addr.s_addr & 0xf0ff == 0x10ac) return -1;
  if(sa->sin_addr.s_addr & 0xffff == 0xa8c0) return -1;
  if(sa->sin_addr.s_addr & 0xff == 0x7f) return -1;
  if(sa->sin_addr.s_addr & 0xff >= 0xe0) return -1;
  return 0;

int main() {
  int r = setjmp(jb);
  switch(r) {
    case 0: {
      SOCKADDR_IN sa;
      int sasize;
      if( WSAStartup(MAKEWORD(2,2), &wd) != 0 ) {
        longjmp(jb, INITERR);
      if( (s = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR ) {
        longjmp(jb, SOCKETERR);
      memset(&sa, 0, sizeof(sa));
      sa.sin_family = AF_INET;
      sa.sin_port = htons(10801);
      sa.sin_addr.s_addr = htonl(INADDR_ANY);
      if( bind(s, (SOCKADDR*) &sa, sizeof(sa)) != 0 ) {
        longjmp(jb, BINDERR);
      for(;;) {
        int r;
        memset(&sa, 0, sizeof(sa));
        sasize = sizeof(sa);
        r = recvfrom(s, buf, 65535, 0, (SOCKADDR*) &sa, &sasize);
        if( r < 1 ) {
          printf("receive error from %s\n", inet_ntoa(sa.sin_addr));
        } else if( buf[0] == BINDREQUEST ) {
          printf("receive bind request from %s\n", inet_ntoa(sa.sin_addr));
          buf[0] = BINDRESPONSE;
          memcpy(&buf[1], &sa, sizeof(sa));
          sendto(s, buf, sizeof(sa) + 1, 0, (SOCKADDR*) &sa, sizeof(sa));
        } else if( buf[0] == CONNECTREQUEST && r == 1 + sizeof(sa) ) {
          SOCKADDR_IN dest;
          printf("receive connect request from %s\n", inet_ntoa(sa.sin_addr));
          buf[0] = CONNECTRESPONSE;
          memcpy(&dest, &buf[1], sizeof(dest));
          if(checkDest(&dest) == 0) {
            memcpy(&buf[1], &sa, sizeof(sa));
            sendto(s, buf, sizeof(sa) + 1, 0, (SOCKADDR*) &sa, sizeof(sa));
          } else {
            puts("bad request!");
    case INITERR: {
      puts("Can't initalize network");
    case BINDERR: {
      puts("Error occur when try binding port");
    case SOCKETERR: {

Hi Folks,
Sharepoint OWSTIMER.EXE causes a high CPU usage in the server. Is there any hotfix or workaround available. Not able to find a proper solution.

We are Using Wss 3.0 Service Pack 2 

Thanks in Advance,

I have had a problem with my main database server in that CPU usage now peaks more frequently at close to 100%, whilst this can be caused by a whole load of factors, I will like to know what steps are best to take in such situations in terms of identifying the cause.

What i have started with is having perfmon and profiler running then combining results together, anything else I can do. I do realise this started after database schema changes.


We are currently having big issues with our CRM system. It has been split across three servers (database, asynch, and front end), and the asynch server is now constantly running at about 100% CPU. This is mostly made up of W3WP and the CrmAsyncService executables, and all background jobs are being massively delayed (e.g. several hours between an email being received and finally having it's workflows complete). We also have large numbers of system jobs waiting for resource.

We have tried:

- Purging AsyncOperationBase

- Rebooting all three servers

- Resetting IIS

None of these have made any difference.

Does anyone please have any clues what might be causing these processes to run like this?


I have a CPU intensive app with multi-thread, during the running time, the system is very slow.

Using AMD codeanalyst try to figure out which part is CPU hotspot, i found the funciton KiDispatchInterrupt() take 60% of CPU usage.

Then I check it using processor explorer,

Top two time consuming threads are

 MSVCRT90.dll! endthreadex+0x6f

MSVCRT90.dll!  endthreadex+0x6f

in the thread, check stack:


I check stacks for several times, each time

ntkrnlpa.exe!KiUnexpectedInterrupt+0x121 and

always on the top, can anyone help me.





I have been given some number of servers(instances) and I do not know on what basis the databases are placed on these instances. Now these databases are to be moved to new hardware on different data center. How do I determine a suitable consolidation strategy for determining the ideal candidates of databases for phase1. Do I have to login on each and every server and find out some entities. If yes what are those ? Can some please suggest me a solution on how do I group those databases for a consolidation on new hardware.

Thanks in advance,



I have the following hardware:

AMD Opteron 252 @ 2.61Ghz

This is a dedicated machine for TFS. It runs only SQL Server 2005 Standard Edition with SP2, WSS2 and TFS with TFS SP1 installed. I am the only one using it since it hasn't gone live yet. I am experiencing high CPU usage by the SQL Server process, peaks to 90% with an average of 40%, but I am not able to pinpoint the problem.

I have a total of 3 Team Projects which I have created for testing purposes. Because of the high CPU usage I sometimes get presumably timeouts when i open the "Work Items" folder. also when I try to create a new Team Project I have to wait for about a minute before I can choose from the installed Process Templates.

I do believe that this started with the installation of Service Pack 2 for SQL Server 2005. Can someone help me troubleshooting this? Or figure out what is causing this high CPU usage and how to solve this. This TFS will be used by about 30 and I have to explain my manager why I am already experiencing these kind performance issues with only one user.


I look all over the web and no luck. I tried out some of other people code but the results is not what I want. What I want to do is display the CPU % in my label of a certain process for example iexplore. I have a timer on my form so it should refresh in less then a second. This is what I have so far but it keeps displaying 0. Can someone help?

PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", "iexplore");
      label1.Text = "CPU Useage: " + counter.NextValue();
This code is part of my function which gets call ever 66 milliseconds.


Until now, I was working on one of my project in VS 2005 without having any issues. But, recently is started to fail closing the solution on that project. When I try to close the solution or the VS itself, VS freezes and won't respond at all. I checked for CPU usage from Task Manager, and I could see that devenv.exe was using almost all the CPU bandwith (90-100%). I couldn't even do anything outside VS, except shutting devenv.exe down from Task Manager.

I have VS 2005 Professional with SP2 installed. This does not happen to other projects I'm working on. I can't remember what changes I might have made before it stopped closing the solution properly. One weird thing that I noticed is that when I open the solution and try to close it without making any changes (not even opening files or changing anything on the screen), it asks me if I want to save changes to the project. I didn't make any changes, why would it ask me to save it or not??? I tried closing after saving when it asked me to, and stilll I have the same problem, freezing and high CPU usage.

Did anybody face this problem before? I would really appreciate any advice on how to troubleshoot this. I've tried everything I could up to this time, but nothing helped.

Thank you!!!



Hi all,

I have SQL Server 2008 (SP1) on Windows Server 2003 (R2).

Sometimes this server becomes very slow and task manager indicates high CPU usage. I added all SQL Server related threads in Performance Monitor to monitor Processor Time% per Thread.

By correlating Thread ID and KPID, I realized that this abnormal increase for CPU usage is always related to SPID #1 which is system process thus cannot be killed. After restarting SQL Server, everything works fine but after few minutes, exactly the same situation happens and SPID #1 consumes almost whole capacity of processors. I tried different ways to determine the source of problem. First I took our main database (financial) to offline state, and turned it back online. All users for this database were killed and SPID #1 released the processor! Sometimes this solution does not work and I use a loop to kill all users in every database. This works in most of times, but today I encountered situation that even killing all users did not work and I forced to restart the SQL Server engine several times during the day.

I was wondering if somebody could suggest a test for further observation or any solution for this issue.

Many thanks in advance,



Hi all,

I need to retrieve the top 5 process parameters running in task manager based on cpu usage. Top 5 is rated based on cpu utilisation. More the utilisation result in top. Is there any library functions or commands to retrieve the same either in C# or ASP .net

Waiting for quicky replies..

Thanks in advance..

Sridhar Narasimhan


Hi all,

I need to retrieve the top 5 process parameters running in task manager based on cpu usage. Top 5 is rated based on cpu utilisation. More the utilisation result in top. Is there any library functions or commands to retrieve the same either in C# or ASP .net

Waiting for quicky replies..

Thanks in advance..

Sridhar Narasimhan


Hi, i have an tcp server which is developed for my anti-cheat program. Its very basic and working good, expect one problem. Sometimes cpu usage going very high (%50-%60) and not decrease until restart the program. Its not number about connections because cpu usage can increase with only one client. Here is the my part of client and server code:



Server Side:

namespace magicserv


 class Listener


  MySqlConnection conn = new MySqlConnection("server=localhost; database=" + Bilgiler.DBAdi + "; user id=" + Bilgiler.DBKullaniciAdi + "; password=" + Bilgiler.DBSifresi);

  DataSet ds = new DataSet();

  publicvoid Start()


   TcpListener tcpListner = new TcpListener(Bilgiler.Port);


   for (; ; )


    Socket socket = tcpListner.AcceptSocket();

    ThreadStart threadStart = delegate


     if (socket.Connected)


      NetworkStream AgAkimi = new NetworkStream(socket);

      StreamReader AkimOku = new StreamReader(AgAkimi);

      while (socket.Connected)




        incomingdata behlul = AkimOku.ReadLine();



















    new Thread(threadStart).Start();





Client Side:

  publicstaticvoid FirlatGitsin(string neyi)




    string sakla = Denizalti.EncryptData(neyi);

    TcpClient Istemci = new TcpClient(dedeler.CServerIP, dedeler.CServerPort);

    NetworkStream AgAkimi = Istemci.GetStream();

    StreamWriter AkimYazici = new StreamWriter(AgAkimi);






    FirotLog.LogYaz("Sunucu ile baglanti kurulamadi");



I can't test this problem on local, bacause it never happen when im connected to server, so i can't found the problem with trying. I'm really need some advice about source of the problem. Maybe i can send data as byte with networkstream.write but as ay say i can't make test about that problem.





i'm te new begginer in this forum and in mobile device

i want to ask to you all about monitoring hardware using cell phone especially cpu usage and memory usage. can you all help me, give me some example code, please....

i hope you all can answer my question soon, cause i need to finish my last project for complete my study...

thanks a lot...



I have one web application. in that i have created WCF service.

I am calling one function from javascript to WCF service. which is going to call every 500ms.

which will connect with mysql database and check for updates from database side. if there is some update into the database it will provide popup on client's screen.

But when i am going to connect 10 clients with server. aspnet_wp.exe is taking 100% cpu usage.

we have xenon processer with 4 GB ram.

then also i can max connect 10 clients...

but i need to connect near by 70 persons at a time..

Is that required higher level server configuration?? then which type of configuration.

or there is some problem in to my logic??

please help me as soon as posible.


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure