In this short code snippet, I want to show a simple technique for ensuring only one instance of your .NET application can run at a time.
The technique is below :
using System.Threading; using System.Windows; namespace MyApplication { public partial class App : Application { private Mutex _mutex; public App() { bool aIsNewInstance; _mutex = new Mutex(true, @"Global\" + "MyUniqueWPFApplicationName", out aIsNewInstance); GC.KeepAlive(_mutex); if (aIsNewInstance) return; MessageBox.Show("There is already an instance running.", "Instance already running.", MessageBoxButton.OK, MessageBoxImage.Information); Current.Shutdown(); } } }
What happens is that a Mutex is created when the application starts up and it is given a unique name, in this case, “MyUniqueWPFApplicationName“. If another instance of the application is started up and the Mutex is already created with that name, the application will shut down. You will also notice that there is a prefix to the name (Global\) that makes the unique name global to a sever running terminal services. If you leave off this prefix, then the mutex is considered local.
Read More “Forcing an Application to a Single Instance in C#”