Check Only one instance of program is running

person Jason Huangfolder_openC#, Codelocal_offer, , access_time September 16, 2009

Sometimes we need to make sure only one instance of the program is running, if there’s already an instance running, you probably test and know before you run the same program again. The reason is sometimes the same program can access the same resources and especially in database operations can cause conflict and crash unexpected.

Add this to your using clause:

Using System.Diagnostics;

And copy the following function to your program:
If the function return is not null, that means a process with the same name is running and the function checks the process table to test that.

Private static Process IsInstanceRunning()
{
  Process currentProcess = Process.GetCurrentProcess();
  Process [] procs = Process.GetProcessByName(currentProcess.ProcessName);
  foreach (Process pr in procs)
  {
    	if ((pr.Id != currentProcessor.Id) && (pr.MainModule.FileName == currentProcess.MainModule.FileName))
		return pr;
 
  }
  return null;
}
 
//Then in your program entry point:
//Such as in the following example:
 
static void Main(string[] args)
{
if (PriorProcess() != null)
	{
		Console.Write("Another instance is already running.");
		return;
	}
 
      //if there is no other instance of this program, initialize your program here.
}

Comment

  1. Having read this I thought it was very informative. I appreciate you
    taking the time and energy to put this information together.
    I once again find myself personally spending a lot of time both reading and commenting.
    But so what, it was still worthwhile!

    Here is my site best iphone games 2014

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>