簡體   English   中英

來自while循環的高CPU使用率,檢查按鍵事件

[英]High CPU usage from while loop, checking for keypress event

我有一個帶有兩個線程的控制台應用程序,一個是重復耗時的工作,另一個是檢查用戶是否按下了ESC鍵。 如果按下ESC鍵,則暫停耗時的工作線程,出現“是否確定”消息,如果選擇是,則耗時的工作線程完成其當前循環然后退出。

由於while (!breakCurrentOperation(work)) ;我必須檢查按鍵的代碼是使用了大量的CPU資源while (!breakCurrentOperation(work)) ; 環。 我怎樣才能防止這種情況發生?

碼:

    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。 它將阻止輸入線程,但您的其他線程將繼續處理。 您似乎沒有在輸入線程上執行任何其他操作,因此阻塞不應成為問題。

由於while循環,看起來你的esc鍵按下檢查邏輯在end less loop中運行。 由於這個功能,該功能不斷利用系統資源。

要解決這個問題,請使用Thread.Sleep在循環中使用一些延遲。 1秒延遲將提高很多性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM