gpt4 book ai didi

c# - 控制台应用程序中的高 CPU 使用率

转载 作者:行者123 更新时间:2023-11-30 14:22:42 31 4
gpt4 key购买 nike

我想一直等待在我的控制台应用程序中按下组合键,但我目前这样做的方式似乎在进程运行时使用了大量 CPU。

对于这样的基本任务,感觉应该有更好的方法来执行此操作,但我不确定那是什么,我使用 dotTrace 分析了我的应用程序,发现唯一的热点是下面的这段代码。

enter image description here

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();
}

关于c# - 控制台应用程序中的高 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48401154/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com