Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check If process is running every minute

Tags:

c#

I have this basic code that will check for notepad running every minute.

namespace Watcher
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; ; i--)
            {
                foreach (Process clsProcess in Process.GetProcesses())
                {
                    if (clsProcess.ProcessName.Contains("notepad"))
                    {
                        Console.WriteLine("True");
                    }
                    Console.WriteLine("NFalse");
                }
                Thread.Sleep(10000);
            }
        }
    }
}

The problem is that it returns "NFalse" for every running process (It will print 100 of them for example). How can I just make this print once to show that the process is not running?

like image 787
user1372896 Avatar asked Aug 23 '12 21:08

user1372896


2 Answers

Refactor your code.

You're doing too much in one method. Put your code that checks to see if notepad is running into a separate method:

static bool CheckIfProcessIsRunning(string nameSubstring)
{
    foreach (Process clsProcess in Process.GetProcesses())
    {
        if (clsProcess.ProcessName.Contains(nameSubstring))
        {
            return true;
        }
    }
    return false;
}

You could simplify this further using LINQ:

static bool CheckIfProcessIsRunning(string nameSubstring)
{
    return Process.GetProcesses().Any(p => p.ProcessName.Contains(nameSubstring));
}

Once you have written this method, all that remains is to call it and print the right message depending on whether it returns true or false.

while (true)
{
    string message = CheckIfProcessIsRunning("notepad") ? "True" : "NFalse";
    Console.WriteLine(message);
    Thread.Sleep(10000);
}

Now instead of one long method with complex logic, you have two very simple methods.

like image 88
Mark Byers Avatar answered Oct 04 '22 18:10

Mark Byers


You just need to check the process you are interested in. Don't bother looping over all the running processes. Use Process.GetProcessByName().

for (int i = 0; ; i--)
{
     Process[] processes = Process.GetProcessByName("notepad++"); // Without extension
     if(processes.Length > 0){
          Console.WriteLine("True");
     }
     else{
          Console.WriteLine("False");
     }

     Thread.Sleep(10000);
}
like image 24
Ian Dallas Avatar answered Oct 04 '22 19:10

Ian Dallas