我有一個包含兩個線程的控制檯應用程序,一個正在做重複的耗時工作,另一個正在檢查用戶是否按下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