EpicDev
EpicDev

Reputation: 33

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? p.s: I tried some duplicate questions etc and I didn't get it to work.

Upvotes: 0

Views: 512

Answers (1)

Daniel Lord
Daniel Lord

Reputation: 782

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 task manager ensure all chrome processes are closed, even if your chrome web browser is closed, there might be some open here. I used msedge, and it seemed to work just fine.

  • You may have hard looped your UI thread. 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. 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. As this will cause all of your processes to lag, not a good thing for production enviroments.

Upvotes: 2

Related Questions