Go to home page mail me! RSS Feed
FoxMetrics Web Analytics

Determine if a process is already running

Monday, January 14, 2008 9:56 AM

Once you start building applications that run every so often for an undefined/unknown amount of time, its very possible that two processes may overlap. 

For example, if you have a schedule task that executes a console application every 5 mins, it is possible that very much possible that it will execute another before the previous one completes. So, how do we determine if a process is already running? 

So far I've seen three ways of doing it.

  1. Use the Singleton pattern
  2. Use Mutex
  3. Use System.Diagnostics (my preffered method)

 

/// <summary>
/// Determines if this process is already running, if so it will kill itself.
/// </summary>
static void ExitIfRunning()
{
    System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
    string processName = process.ProcessName;
    if (System.Diagnostics.Process.GetProcessesByName(processName).Length > 1)
    {
        System.Diagnostics.Process.GetCurrentProcess().Kill();
    }
}

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 7 and 1 and type the answer here:

Preview Your Comment.

 
Next entries »