2011-03-02 34 views
1

有没有办法在控制台应用程序中运行进程,并且在执行期间如果按下空格键,请使用应用程序的状态更新控制台?我们有一个分析文件进行格式化的过程,在执行过程中,状态不会更新。在执行过程中是否有类似于CTRL-C委托方法捕获键盘事件的方法?C# - 控制台应用程序执行期间捕获空格键

TL/DR:在运行过程中,使用空格键更新屏幕状态。

C#控制台应用程序。

回答

2

很好,但你需要一个后台线程进行实际处理。基本上,只需让您的控制台进程在后台线程中启动文件解析,然后在工作时循环检查按键和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. 
} 
+0

非常感谢!我将不得不更多地了解线程工作方式,但这是一个好的开始。再一次感谢你的帮助。 – JRidely 2011-03-02 20:39:09

相关问题