How to achieve 100% cpu load with c# code [duplica

2019-04-02 23:20发布

问题:

This question already has an answer here:

  • thread get 100% CPU very fast 5 answers

I have a task to get a piece of c# code to make my CPU go 100% consistently. I have tried infinite loops, big integer calculations, concatenation of numerous very long strings.... everything either goes to 100% for a few moments and then down to like 60% or doesn't go to 100% at all.

Is there a simple piece of code that can achieve this?

Also using Windows 10

回答1:

You would want to implement threading for this as was previously stated. Your thread would call a method that contains a while(true) loop. For example:

Random rand = new Random()
List<Thread> threads = new List<Thread>();

public void KillCore()
{
     long num = 0;
     while(true)
     {
          num += rand.Next(100, 1000);
          if (num > 1000000) { num = 0; }
     }
}

public void Main()
{
     while (true)
     {
          threads.Add( new Thread( new ThreadStart(KillCore) ) );
     }
}

You don't have to add the threads to a list but you may want to if you somewhere down the road want to call Thread.Abort() to kill them off. To do this you would need a collection of some sort to iterate through and call the Abort() method for every Thread instance in the collection. The method to do that would look as follows.

public void StopThreads()
{
     foreach (Thread t in threads) { t.Abort(); }
}


回答2:

use parallel for to maximize the CPU Cores usage and get the best of threading , inside each thread create an infinite loop using while(true) and congratulations you have **** your CPU :D