Mutex

Intro

Mutex is an OS-backed synchronization primitive that enforces single-owner access to a critical section. In .NET it is most useful for cross-process coordination via named mutexes — for example, ensuring only one instance of a Windows service writes to a shared log file, or preventing concurrent database migrations from two deployment slots. For purely in-process code, lock or SemaphoreSlim is a better default because they avoid the kernel transition overhead that makes Mutex 10-50x slower than Monitor.Enter for uncontended acquisitions.

How It Works

Mutex has ownership semantics:

Example

using var mutex = new Mutex(initiallyOwned: false, name: "MyApp.SingleWriter");

if (!mutex.WaitOne(TimeSpan.FromSeconds(1)))
{
    return;
}

try
{
    WriteSharedFile();
}
finally
{
    mutex.ReleaseMutex();
}

Single-instance application guard using a global mutex:

// Global\ prefix makes the mutex visible across all Terminal Services sessions on Windows
const string MutexName = @"Global\MyApp.SingleInstance";
using var mutex = new Mutex(initiallyOwned: false, name: MutexName, createdNew: out bool created);

if (!mutex.WaitOne(0)) // non-blocking check
{
    Console.Error.WriteLine("Another instance is already running.");
    return;
}
try
{
    RunApplication();
}
finally
{
    mutex.ReleaseMutex();
}

Pitfalls

Tradeoffs

Questions


Whats next