我正在我的机器上做这个测试。显然 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%。如果我使用 …