c#-while循环中的CPU使用率很高,检查按键事件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-while循环中的CPU使用率很高,检查按键事件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1757字,纯文字阅读大概需要3分钟。
内容图文
![c#-while循环中的CPU使用率很高,检查按键事件](/upload/InfoBanner/zyjiaocheng/664/78bcaa4a9d7e495eb68ebf21493d3db5.jpg)
我有一个具有两个线程的控制台应用程序,一个正在执行重复的耗时工作,另一个正在检查用户是否按下了ESC键.如果按下ESC键,则耗时的工作线程将暂停,并显示一条“您确定”消息,如果选择“是”,则耗时的工作线程将完成其当前循环,然后退出.
由于while(!breakCurrentOperation(work));我必须检查按键的代码占用了大量CPU资源.环.如何防止这种情况发生?
码:
public void runTimeConsumingWork()
{
HardWork work = new HardWork();
Thread workerThread = new Thread(() => work.StartWorking());
workerThread.Start(); // Start the hard work thread
while (!workerThread.IsAlive) ; // Hault untill Thread becomes Active
// Check if the user wants to stop the hard work
while (!breakCurrentOperation(work)) ;
// Cancle the hard work
work.Stop();
// Notify the User
UserInterfaceController.WriteToConsole("Operation Cancled...");
}
public static bool breakCurrentOperation(HardWork work)
{
if (Console.KeyAvailable)
{
var consoleKey = Console.ReadKey(true);
if (consoleKey.Key == ConsoleKey.Escape)
{
work.Pause(); // Pause
UserInterfaceController.WriteToConsole("Do you want to stop the current process? \nType s to stop or c to continue.");
string input = Console.ReadLine();
if (input == "c" || input == "C")
{
work.Pause(); // Unpause
return false; // Continue
}
else if (input == "s" || input == "S")
{
return true; // Break the loop
}
else
{
UserInterfaceController.WriteToConsole("Error: Input was not recognized, the current process will now continue. Press Esc to stop the operation.");
work.Pause(); // Unpause
}
}
}
return false;
}
如果我在主控制台UI线程中放置Thread.Sleep(2000),CPU使用率将下降,但是应用程序将无响应,并延迟2秒.
解决方法:
您是否真的需要不断轮询输入内容?如果您正在等待单独线程中的输入,则只需使用Console.ReadKey.它将阻塞输入线程,但是您的其他线程将继续处理.您似乎在输入线程上没有做任何其他事情,因此阻塞不应该成为问题.
内容总结
以上是互联网集市为您收集整理的c#-while循环中的CPU使用率很高,检查按键事件全部内容,希望文章能够帮你解决c#-while循环中的CPU使用率很高,检查按键事件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。