流程是否实时运行

时间:2019-02-03 12:14:49

标签: c#

是否可以实时跟踪过程? 例如,我有一个与游戏相关的应用程序。如果游戏正在运行,则该按钮起作用;如果游戏已关闭,则该按钮等待游戏开始。 如何实现呢? 我找到了这段代码,但是我的不是很好:)

while (true)
{
     System.Diagnostics.Process[] procs = 
     System.Diagnostics.Process.GetProcessesByName("notepad");
     if (procs.Count() == 0)
          break;
}

1 个答案:

答案 0 :(得分:1)

您包含的代码段可以工作,但是它非常占用资源,并且还会阻塞执行线程。您可以使用Timer事件来检查进程状态。

Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
     System.Diagnostics.Process[] procs = 
         System.Diagnostics.Process.GetProcessesByName("notepad");

     //isButtonEnabled is needed to be defined on the upper context
     isButtonEnabled = procs.Count() != 0

}