A lightweight .NET library that ensures only one instance of an application is running at a time. Uses a JSON-serialized PID file with multi-attribute process verification (PID, name, start time, executable path) for accurate instance detection, built-in race condition handling for simultaneous startups, and backward compatibility with legacy PID formats. Supports .NET 10.0 through .NET Standard 2.0.
$ dotnet add package ktsu.SingleAppInstanceA .NET library that ensures only one instance of your application is running at a time.
ktsu.SingleAppInstance is a lightweight .NET library that provides a robust mechanism to ensure only one instance of an application is running at a time. It uses a JSON-serialized PID file with multi-attribute process verification to accurately detect running instances, making it ideal for desktop applications, services, or any software that requires instance exclusivity to prevent resource conflicts or maintain data integrity.
ExitIfAlreadyRunning() for automatic exit and ShouldLaunch() for custom logicInstall-Package ktsu.SingleAppInstance
dotnet add package ktsu.SingleAppInstance
<PackageReference Include="ktsu.SingleAppInstance" Version="x.y.z" />
The simplest way to use SingleAppInstance is to call ExitIfAlreadyRunning at the start of your application. If another instance is detected, the process exits automatically:
using ktsu.SingleAppInstance;
class Program
{
static void Main(string[] args)
{
SingleAppInstance.ExitIfAlreadyRunning();
// Your application code here
Console.WriteLine("Application is running.");
}
}
If you prefer to handle the duplicate-instance case yourself, use ShouldLaunch() which returns a boolean:
using ktsu.SingleAppInstance;
class Program
{
static void Main(string[] args)
{
if (SingleAppInstance.ShouldLaunch())
{
// Your application code here
Console.WriteLine("Application is running.");
}
else
{
Console.WriteLine("Another instance is already running.");
}
}
}
using System.Windows;
using ktsu.SingleAppInstance;
namespace MyWpfApp
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!SingleAppInstance.ShouldLaunch())
{
MessageBox.Show("Application is already running.");
Shutdown();
return;
}
MainWindow = new MainWindow();
MainWindow.Show();
}
}
}
SingleAppInstanceA static class that provides single-instance enforcement for applications. Uses a PID file stored in the application data directory to track running instances.
| Name | Return Type | Description |
|---|---|---|
ExitIfAlreadyRunning() | void | Checks if another instance is running and calls Environment.Exit(0) if so |
ShouldLaunch() | bool | Writes a PID file, waits 1 second for race condition detection, and returns true if safe to proceed |
Contributions are welcome! Feel free to open issues or submit pull requests.
This project is licensed under the MIT License. See the LICENSE.md file for details.