The previous section describes how to use GetTickCount () to control time slice switching. However, MS. net framework also provides the PerformanceCounter object to obtain various performance data of system resources. With this PerformanceCounter object, we can obtain CPU information more accurately.
Last connection: http://www.bkjia.com/kf/201110/107757.html
View plain
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Diagnostics;
Namespace cpu_3_csharp
{
Class Program
{
Static void Main (string [] args)
{
Float level = 150F;
PerformanceCounterCategory [] test = PerformanceCounterCategory. GetCategories ();
For (int I = 0; I <test. Length; I ++)
{
// Console. WriteLine (test [I]. CategoryName );
If (test [I]. CategoryName = "Processor ")
{
String [] temp = test [I]. GetInstanceNames ();
// Console. WriteLine (temp. Length );
For (int j = 0; j <temp. Length; j ++)
{
Console. WriteLine (test [I]. MachineName );
Console. WriteLine ("------------------------");
Console. WriteLine (temp [j]);
Console. WriteLine ("------------------------");
PerformanceCounter [] counters = test [I]. GetCounters (temp [j]);
For (int k = 0; k <counters. Length; k ++)
{
Console. WriteLine (counters [k]. CounterName );
}
}
}
}
Console. writeLine ("************************************* ******************");
PerformanceCounter p = new PerformanceCounter ("Processor", "% Processor Time", "_ Total ");
Console. WriteLine (p. NextValue ());
While (true)
{
// Console. WriteLine (p. NextValue ());
If (p. NextValue ()> level)
{
System. Threading. Thread. Sleep (10 );
}
}
}
}
}
In the Console. writeLine ("************************************* ******************"); the operation before the statement is not required for the moment, because I use it for testing.
By setting a level value, when the CPU usage exceeds this value, it will sleep, otherwise it will not stop empty loops.
However, the results are not ideal, because the kernel is busy and idle as in the previous section, and the problem of dual-core processor will be solved later.
From: Watkins. Song chanllege yourself