我有一个包含两个线程的控制台应用程序,一个正在做重复的耗时工作,另一个正在检查用户是否按下ESC键。如果按下ESC键,耗时的工作线程暂停,将出现“是否确定”消息,如果选择是,则耗时的工作线程完成其当前循环,然后退出。来自while循环的高CPU使用率,检查keypress事件
由于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秒的延迟。
尝试'Thread.Sleep(10);'应用程序会感觉响应,但你不会占用CPU。该任务的另一种方法是在用户请求停止时将字段布尔“_stopRequested”设置为true,并在'workerThread'中检查是否必须停止每个循环周期。 – SimpleVar
这确实有用。我想知道是否有任何方法可以重构此代码,以便主线程无限期地停止,直到发生按键事件时为止? –
已更新我的评论。在main中添加一个简单的'ReadLine()',并且它正是你所描述的。 – SimpleVar