There are many ways to keep running single instance of your application. In this article i'll explain how you can use Mutex and GetProcesses to keep single instance of your application.
Mutex
Mutex is threading synchronisation mechanism. Named mutex works across multiple applications. I've explained more about Mutex in my previous article under Threading. Below example demonstrated how mutex is used to keep single instance of your console application.
Code –
class Program
{
static void Main(string[] args)
{
bool isFirstInstance;
using (Mutex mutex = new Mutex(true, "MyApp", out isFirstInstance))
{
if (isFirstInstance)
{
Console.WriteLine("Welcome, Running first instance of MyApp");
Console.Read();
}
else
{
Console.WriteLine("One instance of MyApp is already running.");
Console.Read();
}
}
}
}
Output –
Similar code you can do for WPF application.
Code –
public partial class App : Application
{
private static Mutex mutex = null;
protected override void OnStartup(StartupEventArgs e)
{
bool isFirstInstance;
mutex = new Mutex(true, "MyWPFApp", out isFirstInstance);
if (isFirstInstance)
{
MessageBox.Show("Welcome,
Running first instance of MyWPFApp", "Info");
MainWindow window = new MainWindow();
window.Show();
}
else
{
MessageBox.Show("One
instance of MyWPFApp is already running.", "Info");
Application.Current.Shutdown();
}
base.OnStartup(e);
}
}
Output –
GetProcesses
One more way to check single instance of your running application using Get Processes. See
below example.
static void Main(string[] args)
{
//get process count of your application
if (System.Diagnostics.Process.GetProcessesByName(
System.IO.Path.GetFileNameWithoutExtension(
System.Reflection.Assembly.GetEntryAssembly().Location)).Count()
> 1)
{
Console.WriteLine("One instance is already running so closing this instance");
Console.Read();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
else
{
Console.WriteLine("Welcome, Running first instance.");
Console.Read();
}
}
You can download code from Gist.
Thank you for reading this article. Please
leave your feedback in comments below.
Reference –
See also –