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?
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:
You could simplify this further using LINQ:
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.
Now instead of one long method with complex logic, you have two very simple methods.