singleinstanceprogram 1.0.2

dotnet add package singleinstanceprogram --version 1.0.2
                    
NuGet\Install-Package singleinstanceprogram -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="singleinstanceprogram" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="singleinstanceprogram" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="singleinstanceprogram" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add singleinstanceprogram --version 1.0.2
                    
#r "nuget: singleinstanceprogram, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package singleinstanceprogram@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=singleinstanceprogram&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=singleinstanceprogram&version=1.0.2
                    
Install as a Cake Tool

SingleInstanceProgram

A helper class to ensure your program runs as a single instance.
Additional instances send their arguments to the first instance via IPC.
The first instance can optionally respond back to the secondary instances. Note: A thread is spawned for IPC.


Usage

Installation Instructions

Using .NET CLI
dotnet add package singleinstanceprogram
Using the Package Manager Console (Visual Studio)
Install-Package SingleInstanceProgram
Using csproj

Add the following to your project file:

<ItemGroup>
  <PackageReference Include="SingleInstanceProgram" />
</ItemGroup>

Quick Start

using SingleInstanceProgramNS;

// Create instance (uniqueId = app identifier, args = arguments secondary launches should send to the first instance)
SingleInstanceProgram s = SingleInstanceProgram.Create("UniqueId", args);

// Subscribe to events
s.MessageReceivedFromFirstInstance += (sender, e) =>
{
    if (e.Message != null)
        Console.WriteLine("From first instance: " + string.Join(" ", e.Message));
};

s.MessageReceivedFromOtherInstance += (sender, e) =>
{
    if (e.Message != null)
        Console.WriteLine("From other instance: " + string.Join(" ", e.Message));

    // Respond back to sender
    e.RespondToOtherSender?.Invoke(["Hello from first instance!"]);
};

// Start background IPC thread
s.Start();

// Process this instance’s args manually (first instance only)
foreach (var arg in args)
    Console.WriteLine(arg);

After completing the steps above, your program should be running as a single instance. Additional launches will pass their args to the first instance.


In detail explanation

Events
Event Raised By When Response Available
MessageReceivedFromOtherInstance First instance A new (secondary) instance starts RespondToOtherSender (send reply to that secondary instance)
MessageReceivedFromFirstInstance Secondary instance First instance replies RespondToOtherInstance is always null

Event Args: MessageReceivedEventArgs
  • string[]? Message → Arguments from the other instance.
  • Action<string[]>? RespondToOtherSender → Only non-null in the first instance; use to reply.

Lifecycle
  1. Call Create("UniqueId", args) → creates named mutex + IPC channels.
  2. Subscribe to events before calling Start().
  3. Call Start() → begins background thread for listening.
  4. Manually process first-instance args (since no event fires for them).
  5. (Optional) On shutdown, unsubscribe from events.
  6. (Optional) Call Stop() to release named mutex + IPC channels

Notes

  • Event handlers are invoked from a background thread — marshal back to the UI thread if needed.
  • The UniqueId must be stable and unique per app; otherwise, instances may conflict.
  • The listening thread runs until either the process exits or Stop() is called.

How it's made

I implemented a singleton constructor to ensure that only one instance of the class is alive so that the first instance can't act like a second instance.

When the Start() method is called, a named mutex is created with the unique ID provided. This mutex acts as a system-wide lock:

  • If the mutex can be acquired, this process is the first instance. A background thread is then started to listen for connections from other instances using a named pipe server.

  • If the mutex cannot be acquired, this process is a secondary instance. Its arguments are sent to the first instance over a named pipe client, and the process then exits immediately.

The communication between instances is handled with named pipes:

  • The first instance runs a loop (ListenForClients) that waits for other processes to connect. When a connection is made, it reads the message, wraps it into a MessageReceivedEventArgs, and triggers the MessageReceivedFromOtherInstance event.

  • The event args also expose an Action<string[]> RespondToOtherSender which lets the first instance send a response back through the same pipe.

  • On the other side, when a secondary instance sends its arguments, it waits for a possible reply from the first instance. If a response is received, the MessageReceivedFromFirstInstance event is triggered.

Events (MessageReceivedFromOtherInstance and MessageReceivedFromFirstInstance) are exposed so that user code can hook into this IPC flow without worrying about mutexes, pipes, or threading details.

Lessons learned

  • How to use named mutexes to manage single-instance enforcement.
  • How to use named pipes with StreamReader/StreamWriter for IPC.
  • How to expose a callback function in event args without exposing internal state (RespondToOtherSender).
  • How to implement a singleton pattern that takes parameters safely.
  • How to safely exit/abort a thread using cancellation tokens, including blocking threads
  • How to write integration unit tests.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 173 9/26/2025
1.0.1 152 9/26/2025
1.0.0 191 9/26/2025 1.0.0 is deprecated.

Added a stop function to manually stop and release single instance resources.
Fixed unit tests failing bug.