[英]High CPU usage in console application
我想不斷等待在我的控制台應用程序中按下一個組合鍵,但我目前正在這樣做的方式似乎在進程運行時使用了大量的CPU。
對於這樣一個基本任務,感覺應該有更好的方法來做到這一點,但我不確定那是什么,我用dotTrace描述了我的應用程序,發現唯一的熱點是下面這段代碼。
while (true)
{
if (!Console.KeyAvailable)
{
continue;
}
var input = Console.ReadKey(true);
if (input.Modifiers != ConsoleModifiers.Control)
{
continue;
}
if (input.Key == ConsoleKey.S)
{
Server?.Dispose();
}
}
如果您使用標准Ctrl + C退出而不是Ctrl + S,則可以使用簡單的ReadKey
。 並確保TreatControlCAsInput
設置,然后,應用程序將被殺死。
static void Main(string[] args)
{
// important!!!
Console.TreatControlCAsInput = true;
while (true)
{
Console.WriteLine("Use CTRL+C to exit");
var input = Console.ReadKey();
if (input.Key == ConsoleKey.C && input.Modifiers == ConsoleModifiers.Control)
{
break;
}
}
// Cleanup
// Server?.Dispose();
}
而不是在循環中觀察它,使用按鍵事件來檢查每次按下鍵。
這意味着您只需為每次按鍵檢查一次。
編輯:我錯過了控制台應用程序部分,但你可以讀取這樣的行:
來自: https : //www.dotnetperls.com/console-readline
using System;
class Program
{
static void Main()
{
while (true) // Loop indefinitely
{
Console.WriteLine("Enter input:"); // Prompt
string line = Console.ReadLine(); // Get string from user
if (line == "exit") // Check string
{
break;
}
Console.Write("You typed "); // Report output
Console.Write(line.Length);
Console.WriteLine(" character(s)");
}
}
}
不需要繁忙的等待。 Console.ReadKey()
將阻塞,直到按鍵可用,基本上沒有CPU使用率。 因此,您無需一遍又一遍地檢查Console.KeyAvailable
。
while (true)
{
// DO NOT INTERCEPT KEY PRESSES!
//IF CTRL+S IS FORWARDED TO THE CONSOLE APP, WEIRD THINGS WILL HAPPEN.
var input = Console.ReadKey(false);
if (input.Modifiers != ConsoleModifiers.Control)
{
continue;
}
if (input.Key == ConsoleKey.S)
{
Server?.Dispose();
}
}
我認為你應該使用Thread.Sleep
while (true)
{
Thread.Sleep(100);
if (!Console.KeyAvailable)
{
continue;
}
var input = Console.ReadKey(true);
if (input.Modifiers != ConsoleModifiers.Control)
{
continue;
}
if (input.Key == ConsoleKey.S)
{
Server?.Dispose();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.