[英]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.