Creating a single instance application in C#, WPF
Some time you might want the user to run only one instance of the application. Its pretty easy to do so in C#. This is acheived using a Mutex. A mutex is used to restrict the usage of common resources in concurrent proragmming. C# provides a class called System.Threading.Mutex with which we can control the number of instances of an application that should be running. Just add the following snippet to the App.xaml.cs file (code behind file of App.xaml)
class App : Application
{
private Mutex myMutex;
...
protected override void OnStartup(StartupEventArgs theArgs)
{
bool aIsNewInstance = false;
myMutex = new Mutex(true, "Foo.SingletonApp", out aIsNewInstance); //Creates a mutex for the application
if(!aIsNewInstance)
{
App.Current.Shutdow(); //Shutdown when a new mutex with the same name is created
}
}
}
How this works
The creation of a mutex in here takes three parameters. First one is to give the ownership of this mutex to the calling thread. Second one is the unique name given for this mutex (remember this is a unique name). Third one is an out parameter that returns
true — if there are no mutex with this name and if the new mutex is successfully created
fase — if there is already a mutex with this name.
That why we check for !aIsNewInstance in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the application.


What about the call to base.OnStartup?
Adrian Alexander
6 Jan 10 at 9:05 pm
I suggest more elegant solution: http://blogs.microsoft.co.il/blogs/maxim/archive/2010/02/13/single-instance-application-manager.aspx
Maxim
19 Feb 10 at 3:55 pm