How to stop running multiple instances of my App in C#?

  • Thread starter Thread starter PalB
  • Start date Start date
PalB said:
How to stop running multiple instances of my App in C#?

The easiest ways are to either acquire a named mutex, or try to open a
socket on a port which nothing but your app would use. Of course, both
are problematic in terms of namespace - creating a name no-one else is
likely to use for a mutex is easier than working out a port number
which no-one else is likely to use though.
 
PalB said:
How to stop running multiple instances of my App in C#?

I check to see if the program is already running in Main before the call to
the actual object to run it.

Of course this assumes that your program name is unique, therefore if you
have another application with the same Name, it won't run at all...

static void Main(){
if( System.Diagnostics.Process.GetProcessesByName(
"ProgramNameHere" ).Length > 1 ){
return;
}
}
 
PalB said:
Hi i am writing code like this.....is it ok?

static void Main()
{
bool isNew = false;
Mutex mtx = new Mutex( true, "MyApp_Mutex", out isNew );
if( !isNew )
{
MessageBox.Show( "MyApp is already running." );
return;
}
}

You don't need to specify the initial value for isNew - out parameters
don't need to be definitely assigned beforehand.

Other than that, it looks okay to me - have you tried it?
 
Back
Top