我正在我的机器上做这个测试。显然 cpu % 会有所不同,但我更想了解发生了什么。我只是创建了一个新的空白控制台 .Net Framework 应用程序(--not-- .net core)。这是“Program.cs”的来源:
static void Main(string[] args)
{
myClass myClass = new myClass();
myClass.myInifiniteMethodAsync();
Console.WriteLine("Launched...");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
那么这是 myClass 的来源:
class myClass
{
public async Task myInifiniteMethodAsync()
{
await Task.Run(() => myInfiniteMethod());
}
public void myInfiniteMethod()
{
//do some things but keep this thread holded...
//bool keepRunning = true;
//while (keepRunning) { } <--- this one takes 30% cpu...
Console.ReadLine(); // <--- this one takes 5% cpu...
}
}
Run Code Online (Sandbox Code Playgroud)
我需要 IfiniteMethod 始终保持在那里,永远“保持”线程。如果我使用“while(true)”方法,CPU 会提升 30%。如果我使用 Console.ReadLine() 方法,CPU 保持在 5% 左右。
我想了解为什么,以及是否有更好的方法来保持线程。
小智 6
为了回答您的问题,我们需要了解操作系统如何执行这些行。
对于while(true) {},编译后的代码由变量的比较组成keepRunning,然后进行条件跳转。它的重要部分是操作系统不断执行指令。
但是,对于Console.ReadLine(),它等待用户输入,为此操作系统只等待硬件中断(按键),不需要连续执行指令。
因此,循环版本要求操作系统给你的程序尽可能多的时间,因为它“想要”运行很多指令,而对于输入版本,操作系统只等待硬件中断,程序不会不需要执行任何其他指令。