title: Constantly monitor processes
body: <p>I've written some code which monitors the running windows processes.
  I wish to know when a certain process starts and when it ends.
  The code works just like I want it to.</p>
  
  <p>Now, I wish to implement it in a windows form server application - so it will run in loop as long as the form is alive. I guess I should make it run asynchronously maybe using a <code>BackgroundWorker</code>. I'm just not sure what's the best way to do it and how.</p>
  
  <p>Here is my monitor code:</p>
  
  <pre><code>using System;
  using System.Management;
  using System.Diagnostics;
  using System.Collections.Generic;
  using System.ComponentModel;
  
  class ProcessMonitor
  {
      public static void Main()
      {
          Dictionary&lt;string, Process&gt; newProcs= new Dictionary&lt;string, Process&gt; ();
          while (true) 
          {
              foreach (Process process in Process.GetProcesses())
              {
                  if (process.ProcessName.CompareTo("Someprocess") == 0)
                  {
                      if (!searchForProcess(newProcs, process.Id))
                      {
                          ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id);
                          foreach (ManagementObject @object in searcher.Get())
                          {
                              Console.Write("Adding new Process: ");
                              Console.WriteLine(@object["CommandLine"] + " ");
                              newProcs.Add(@object["CommandLine"] + " ", process);
                          }   
                      }
                  }
              }
              checkProcesses(newProcs);
          } 
          Console.WriteLine("Done");
      }
  
      private static bool searchForProcess(Dictionary&lt;string, Process&gt; newProcs, int newKey)
      {
          foreach (Process process in newProcs.Values)
          {
              if (process.Id == newKey)
                  return true;
          }
  
          return false;
      }
      private static void checkProcesses(Dictionary&lt;string, Process&gt; newProcs)
      {
          foreach (string currProc in newProcs.Keys)
          {
              bool processExists = false;
              foreach (Process process in Process.GetProcesses())
              {
                  if (process.Id == newProcs[currProc].Id)
                  {
                      processExists = true;
                      break;
                  }
  
              }
              if (!processExists)
              {
                  Console.Write("Process Finished: ");
                  Console.WriteLine(currProc);
                  newProcs.Remove(currProc);
                  if (newProcs.Count == 0)
                      break;
              }
          }
      }
  }
  </code></pre>
  
  <p>Any ideas?</p>