1
有沒有辦法在控制檯應用程序中運行進程,並且在執行期間如果按下空格鍵,請使用應用程序的狀態更新控制檯?我們有一個分析文件進行格式化的過程,在執行過程中,狀態不會更新。在執行過程中是否有類似於CTRL-C委託方法捕獲鍵盤事件的方法?C# - 控制檯應用程序執行期間捕獲空格鍵
TL/DR:在運行過程中,使用空格鍵更新屏幕狀態。
C#控制檯應用程序。
有沒有辦法在控制檯應用程序中運行進程,並且在執行期間如果按下空格鍵,請使用應用程序的狀態更新控制檯?我們有一個分析文件進行格式化的過程,在執行過程中,狀態不會更新。在執行過程中是否有類似於CTRL-C委託方法捕獲鍵盤事件的方法?C# - 控制檯應用程序執行期間捕獲空格鍵
TL/DR:在運行過程中,使用空格鍵更新屏幕狀態。
C#控制檯應用程序。
很好,但你需要一個後臺線程進行實際處理。基本上,只需讓您的控制檯進程在後臺線程中啓動文件解析,然後在工作時循環檢查按鍵和Thread.Yield()語句。如果按下某個鍵,則可以從後臺線程正在更新的某個類獲取狀態更新:
private static StatusObject Status;
public static void main(params string[] args)
{
var thread = new Thread(PerformProcessing);
Status = new StatusObject();
thread.Start(Status);
while(thread.IsAlive)
{
if(keyAvailable)
if(Console.ReadKey() == ' ')
ShowStatus(Status);
//This is necessary to ensure that this main thread doesn't monopolize
//the CPU going through this loop; let the background thread work a while
Thread.Yield();
}
thread.Join();
}
public void PerformProcessing(StatusObject status)
{
//do your file parsing, and at significant stages of the process (files, lines, etc)
//update the StatusObject with vital info. You will need to obtain a lock.
}
public static void ShowStatus(StatusObject status)
{
//lock the StatusObject, get the information from it, and show it in the console.
}
非常感謝!我將不得不更多地瞭解線程工作方式,但這是一個好的開始。再一次感謝你的幫助。 – JRidely 2011-03-02 20:39:09