简体   繁体   English

不断检查进程是否打开

[英]Constantly check if a process is open

I want to constantly check if a background process is running or not, I only have one label (to display the result) My code that shows whether it's running or not is:我想不断检查后台进程是否正在运行,我只有一个标签(用于显示结果)显示它是否正在运行的代码是:

Process[] plist = Process.GetProcessesByName("chrome");
        if (plist.Length > 0)
        {
            label1.ForeColor = Color.Green;
            label1.Text = "FOUND";
        }
        else 
        {
            label1.ForeColor = Color.Red;
            label1.Text = "NOT FOUND";
        }

And when run it, it works, but when I close the process it still shows "FOUND", how can I make it always check if plist.Lenght is 0 or >0?当运行它时,它可以工作,但是当我关闭进程时它仍然显示“找到”,我怎样才能让它始终检查 plist.Lenght 是 0 还是 >0? ps: I tried some duplicate questions etc and I didn't get it to work. ps:我尝试了一些重复的问题等,但没有成功。

using System;
using System.Diagnostics;

namespace Program
{
  class Program
  {
    static void Main(string[] args)
    {
      Process[] plist = Process.GetProcessesByName("msedge");
      if (plist.Length > 0)
      {
        Console.WriteLine(plist[0].ProcessName);
      }
      else
      {
        Console.WriteLine("NotFound");
      }
    }
  }
}

The code above seems to be working just fine.上面的代码似乎工作得很好。 Two things I would check are:我要检查的两件事是:

  • open up task manager打开任务管理器任务管理器 ensure all chrome processes are closed, even if your chrome web browser is closed, there might be some open here.确保所有 chrome 进程都关闭,即使您的 chrome 网络浏览器关闭,这里也可能有一些打开。 I used msedge, and it seemed to work just fine.我使用了 msedge,它似乎工作得很好。

  • You may have hard looped your UI thread.您可能已经硬循环了您的 UI 线程。 This means it is so busy checking processes, that it has no time to update your label.这意味着它非常忙于检查流程,以至于没有时间更新您的标签。 normally you do not do tasks like this on the UI thread, but instead break them off on side threads.通常你不会在 UI 线程上执行这样的任务,而是在侧线程上中断它们。 Alternatively you can use a timer on the main thread, check every couple of miliseconds.或者,您可以在主线程上使用计时器,每隔几毫秒检查一次。 The last but Bad way to do this is to call:最后但不好的方法是调用:

label1.Invalidate();
Application.DoEvents();

These lines will force the UI to update and pause your process check, but is really only good for testing / development.这些行将强制 UI 更新和暂停您的流程检查,但实际上仅适用于测试/开发。 As this will cause all of your processes to lag, not a good thing for production enviroments.因为这会导致您的所有流程滞后,这对生产环境来说不是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM