Check If process is running every minute

c#

Solution

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.

Problem

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?

Original source