如何使用C#代码实现100%的CPU负载 [英] How to achieve 100% cpu load with c# code
问题描述
我的任务是获取一段C#代码,以使我的CPU始终如一地运行100%.我尝试了无限循环,大整数计算,许多非常长的字符串的串联....片刻之后一切都达到100%,然后下降到60%或根本不达到100%.
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?
也使用Windows 10
Also using Windows 10
推荐答案
您将希望如前所述为此实现线程化.您的线程将调用一个包含while(true)循环的方法.例如:
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) ) );
}
}
您不必将线程添加到列表中,但是如果您想在后面某个地方调用Thread.Abort()可以将其杀死.为此,您需要某种类型的集合来迭代并为集合中的每个Thread实例调用Abort()方法.这样做的方法如下所示.
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(); }
}
这篇关于如何使用C#代码实现100%的CPU负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!