Running a process only once

Wed 25 January, 2006

We all  know that usually the starting point for every WinForms application is the Main() method. Here’s a little trick to ensure that an application of ours runs only once,  making an active effort to stop any other instance that could be called if there’s another one already running. Here’s how:

/// <summary>
///Application’s entry point
/// </summary>
[STAThread]
static void Main() 
{
if(Process.GetProcessesByName(
   Process.GetCurrentProcess().ProcessName).GetUpperBound(
0)==0)
   {
      Application.Run(
new frmMain());
   }
}

Colorized by: CarlosAg.CodeColorizer

 

The key of all this is the Process class. It belongs to the Systems.Diagnostics namespace, and one of its capabilities is obtaining the name of the current process (via Process.GetCurrentProcess().ProcessName, which returns an string), and another one is obtaining all running process with a given name (Process.GetProcessesByName, which returns an array of Process objects).  The if() in that line searches for an already running process with the same name as the one we’re trying to start in the list of all currently running processes and if it’s not found, which is determined by comparing the length of the array containing the found processes with 0, the application starts.

Comments »

The URI to TrackBack this entry is: http://codecruncher.blogsome.com/2006/01/25/running-a-process-only-once/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>