Check if the process is running every minute

I have this basic code that checks that notepad works 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 each running process (for example, it will print 100 of them). How can I just do this listing once to show that the process is not running?

+5
source share
4 answers

Recover your code.

You do too much in one method. Put your code that checks to see if notepad works in a separate method:

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

This can be simplified using LINQ:

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

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

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

.

+7

. . Process.GetProcessByName().

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

     Thread.Sleep(10000);
}
+2

Just change this so that you only print once.

var b = false;
foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains("notepad"))
                {
                    if (!b) b = true;
                }
            }
                Console.WriteLine(b);
0
source

Good thing it works well.

Dim x = Process.GetProcesses().ToList().FirstOrDefault(Function(p) p.ProcessName.Contains("Notepad"))
if x Is Nothing then
    Console.WriteLine("false")
end if
0
source

All Articles