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

若如初见. 提交于 2019-12-05 07:03:44

问题


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



来源:https://stackoverflow.com/questions/49203825/how-to-achieve-100-cpu-load-with-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!