Updated on
A Mutex in C# is a lock that only one thread can own at a time, and once we give it a name, it works across processes too. We call WaitOne() to take ownership, use the shared resource, and call ReleaseMutex() from the same thread to give it back.
Multithreading can significantly boost an application’s performance, but it also brings challenges related to synchronizing and coordinating tasks across different threads (and even processes). With C#, we have a variety of tools at our disposal to overcome these challenges and build a resilient, performant application that makes full use of the available computing resources. One such tool is the Mutex class.
Let’s start.
What Are Synchronization Primitives?
In many cases, trying to access a resource simultaneously from multiple threads will cause corruption. For example, we should only write to a file from one place at a time. Otherwise, the operations will mangle the data up and the file will get corrupt! Synchronization primitives are tools we have at our disposal to safely access these types of resources from a multi-threaded environment. They do this by making sure we don’t make more simultaneous requests to a resource than is acceptable. C# has several of them, and we compare them in our guide to locking mechanisms in C#.
What Is a Mutex in C#?
A Mutex is a synchronization primitive from System.Threading that the operating system provides. It restricts access to a resource so that only one thread can use it at a time.
Unlike lock, it can reach beyond our process. An unnamed Mutex coordinates threads inside one process. Once we give it a name, other processes that open that name share the same Mutex, which is why we see it when several programs write to one file, or when an app must not start twice.
A Mutex also has an owner. The thread that acquires it with WaitOne() is the only thread allowed to release it with ReleaseMutex(). The owner can call WaitOne() again without blocking itself, as long as it calls ReleaseMutex() the same number of times.
If the owning thread ends without releasing it, the Mutex is abandoned, and the next thread that acquires it gets an AbandonedMutexException.
A Mutex restricts access through the concept of ownership: threads must only access the resource protected by the Mutex if they own the Mutex. Any thread may attempt to acquire ownership of the Mutex upon which one of these outcomes may happen:
- If the
Mutexis free, the requesting thread will successfully acquire its ownership - If another thread currently owns the
Mutex, the requesting thread will be blocked until the currently owning thread releases it - If the thread that owns the
Mutexexits without releasing it, the requesting thread still gets ownership, butWaitOnethrows anAbandonedMutexExceptionto warn it.
This means that it is not possible for more than one thread to own the Mutex at once.
A Mutex is also slower than lock. In one run on .NET 10, 100,000 uncontended WaitOne() and ReleaseMutex() pairs took about 50 ms, while the same number of lock blocks on a System.Threading.Lock took about 2 ms. So when every thread lives in one process, lock is the simpler and faster choice. We pick a Mutex when the threads we coordinate belong to different processes, or when we need to wait on several handles at once with WaitHandle.WaitAny().
How Do We Acquire and Release a Mutex?
Let’s create a Mutex using its constructor:
var mutex = new Mutex();
Doing this, we’ll get a Mutex that’s local and that no thread initially owns. If we instead want the current thread to own the Mutex, we can specify the first parameter, initiallyOwned as true. We’ll soon learn what we mean by a local Mutex and also create a Mutex that isn’t local.
We should have a reference to the Mutex object from each thread we might need to access a protected resource in. Once that need arises, from that same thread we want to access the resource, we’ll invoke its WaitOne method:
mutex.WaitOne();
This method will only return once we’ve acquired ownership of the Mutex. After this point, we can safely access the protected resource without the risk of a race condition.
WaitOne() waits for as long as it takes. If we’d rather give up after a while, we pass a timeout, and the method returns true only when we got the Mutex:
if (mutex.WaitOne(TimeSpan.FromSeconds(5)))
{
try
{
// use the protected resource
}
finally
{
mutex.ReleaseMutex();
}
}
When it returns false, we don’t own the Mutex, so we must not touch the resource or call ReleaseMutex().
Once we’re done with the resource, we must take care to release the Mutex so that other threads can acquire it:
mutex.ReleaseMutex();
Only the thread that owns the Mutex may release it. If any other thread calls ReleaseMutex(), it gets an ApplicationException.
If our thread terminates without releasing the Mutex, it will be put in an abandoned state. The next thread that acquires the Mutex will encounter an AbandonedMutexException exception on the WaitOne method. It’s good practice to handle this exception when waiting on a Mutex.
How Do Named Mutexes Work Across Processes?
Local Mutex objects are sufficient for coordinating access to a protected resource in a single process. However, if we have multiple processes that need to access a single resource, we need a Mutex that can span all those processes. We call this type of Mutex a named system Mutex. It has a name associated with it, and other processes can access the same Mutex with its name.
To create a named system Mutex, we provide the name parameter to the constructor (this is the second parameter):
var mutex = new Mutex(initiallyOwned: false, "MyMutex");
All Mutex objects in the same session with this name refer to the same underlying Mutex in the operating system. The rules we discussed still apply: only one thread can own this Mutex at a time (even across different Mutex instances as long as they all have the same name).
We can prefix Mutex names with either Global\ or Local\, and the prefix decides which sessions can see the name. A Global\ name is shared by every process on the machine. A Local\ name is shared only by processes in the same session, and it’s also what we get when we leave the prefix out. In the words of Microsoft’s documentation, “If you do not specify a prefix when you create a named mutex, it takes the prefix Local\.”
What counts as a session depends on the platform. On Windows, it’s a login session, and services usually run in a session of their own, so a service and a desktop app need a Global\ name to share a Mutex. On Linux and macOS, each shell has its own session. Two terminal windows running the same program won’t share a Local\ Mutex at all, which is why our example uses Global\.
Linux and macOS add one more boundary: a named Mutex is restricted to the user that created it by default, so two processes running as different users won’t share it either.
Since .NET 10, we can set the same scope without a string prefix, through NamedWaitHandleOptions:
var options = new NamedWaitHandleOptions { CurrentSessionOnly = false };
using var mutex = new Mutex(initiallyOwned: false, "numbers_output", options);
Setting CurrentSessionOnly to false shares the Mutex across sessions, like the Global\ prefix. CurrentUserOnly stays at its default of true, which keeps the Mutex to the current user. We could set it to false too, but Microsoft warns that on Unix-like systems that’s only safe when every user on the machine, root included, is inside the same trust boundary.
Mutex Example in C#: Writing to One File From Several Processes
Let’s start with a very simple method that writes some data to a file:
public static void WriteNumbers(string fileName)
{
for (int number = 1; number <= 50; number++)
{
File.AppendAllText(fileName, $"{number} ");
Thread.Sleep(100);
}
}
It appends all integers from 1 to 50 to the file each time we execute it.
However, we haven’t implemented any synchronization between threads or processes yet. If we execute this code multiple times simultaneously, we can see multiple different number streams interweaved into the file, or an IOException when two appends collide.
Let’s fix this:
public static void WriteNumbers(string fileName)
{
using var mutex = new Mutex(initiallyOwned: false, "Global\\numbers_output");
mutex.WaitOne();
for (var number = 1; number <= 50; number++)
{
File.AppendAllText(fileName, $"{number} ");
Thread.Sleep(100);
}
mutex.ReleaseMutex();
}
We create a named system Mutex to synchronize access to the file. We then acquire ownership of the Mutex before beginning to write the numbers. Finally, after writing to the file, we release the Mutex.
Now, even if we run this code multiple times simultaneously, we won’t get any interweaving between the different number streams. That’s because we’re only writing to the file while we have ownership of the Mutex, and that can only be the case with one thread at a time.
We tried it with two copies of the sample’s console app, started at the same moment against the same file. The file came out as 1 to 50 twice in a row, with nothing mixed in between. The sample sleeps for 1 millisecond instead of 100 to keep its test fast, so it runs through all 50 numbers in a moment.
What Happens When a Mutex Is Abandoned?
A Mutex is abandoned when the thread that owns it ends without calling ReleaseMutex(). The next thread to acquire it gets ownership as usual, but WaitOne() also throws an AbandonedMutexException to tell it that the previous owner never finished.
Microsoft’s documentation says what that usually means: “An abandoned mutex often indicates a serious error in the code.” Whatever the previous owner was protecting, our file in this case, may be half written.
Our code doesn’t handle that exception, and it doesn’t make sure it releases the Mutex either. If the loop throws, ReleaseMutex() never runs and the Mutex stays owned. Other threads and processes keep waiting for as long as our thread lives. Once it ends, the next one to acquire the Mutex gets the exception.
So we need two fixes: handle an abandoned Mutex when we acquire it, and always release it when we’re done.
Let’s solve that:
public static void WriteNumbers(string fileName)
{
using var mutex = new Mutex(initiallyOwned: false, "Global\\numbers_output");
try
{
mutex.WaitOne();
}
catch (AbandonedMutexException)
{
File.WriteAllText(fileName, string.Empty);
}
try
{
for (var number = 1; number <= 50; number++)
{
File.AppendAllText(fileName, $"{number} ");
Thread.Sleep(100);
}
}
finally
{
mutex.ReleaseMutex();
}
}
Now, if the last owner of the Mutex abandoned it, we assume that the file is corrupt and clear its contents. We’ll then proceed with writing the numbers as usual.
That works because the thread that catches the AbandonedMutexException already owns the Mutex, so the finally block releases it on both paths.
We also guarantee that we call the ReleaseMutex method if the loop throws an exception.
Can We Use a Mutex With async and await?
No, not between WaitOne() and ReleaseMutex(). A Mutex belongs to the thread that acquired it, and an await can resume our method on a different thread.
After an await, the rest of the method usually runs on a thread pool thread. When that thread isn’t the owner, its ReleaseMutex() call throws an ApplicationException. The Mutex stays owned by the original thread, which has long since moved on to other work, and every other waiter keeps waiting for as long as that thread lives.
The compiler won’t warn us about it. It rejects an await inside a lock block, but WaitOne() and ReleaseMutex() are ordinary method calls, so the mistake compiles and only fails at run time.
Inside one process, the usual replacement is a SemaphoreSlim with a count of one and its WaitAsync() method, since a semaphore doesn’t care which thread releases it. Across processes, we keep the code between WaitOne() and ReleaseMutex() synchronous, so one thread runs all of it.
Let’s see it fail. This is code not to copy: the sample’s MutexAsyncPitfall class acquires a Mutex, awaits a short delay, and then tries to release it:
public static class MutexAsyncPitfall
{
public static async Task<string> ReleaseAfterAwait()
{
using var mutex = new Mutex();
var threadBefore = Environment.CurrentManagedThreadId;
mutex.WaitOne();
await Task.Delay(50);
var threadAfter = Environment.CurrentManagedThreadId;
try
{
mutex.ReleaseMutex();
return $"Released on the same thread ({threadBefore}).";
}
catch (ApplicationException ex)
{
return $"{ex.GetType().Name} on thread {threadAfter} " +
$"(acquired on thread {threadBefore}): {ex.Message}";
}
}
}
Running dotnet run -- --async-pitfall in the folder that holds MutexClassInCSharp.csproj prints the result:
ApplicationException on thread 5 (acquired on thread 2): Object synchronization method was called from an unsynchronized block of code.
The thread numbers can differ from ours, and when the method starts on a thread pool thread, it often resumes on that same thread and the release succeeds. That makes the bug easy to miss in testing.
If the code in between has to await, a SemaphoreSlim with a count of one gives us the same one-at-a-time rule with WaitAsync().
Conclusion
With the Mutex class in C#, we can easily overcome a lot of the different challenges we face when trying to access a shared resource from a multi-threaded environment. We can offload the heavy lifting to the operating system and rely on its guarantees to write safe, performant code that makes the maximum use of all the resources it has available.
Just remember that a Mutex belongs to the thread that took it, so keep await out of the code it protects, and give a cross-process Mutex a Global\ name when the processes may run in different sessions.
Tested with .NET 10.0.10 and xUnit 2.9.3.







Can you use the global named mutex across different applications like in a microservice architecture to ensure that one Microservice waits for the other before accessing the resource?
Also, in an asynchronous messaging system where there is a sender and a listener, can mutex prevent the listener from accessing the resource until the sender releases it?
If your microservices are running on the same machine, then yes, it would theoretically be possible to synchronize access to a shared resource using a Mutex. However, doing so defeats the point of microservices, and in practice, you should almost never do that. Two reasons why:
One exception would be if the resource itself is specific to the machine, such as a file. Generally, microservices shouldn’t be directly accessing shared files anyhow (because they shouldn’t share resources), but if you do have that for any reason, a named system Mutex can help.
For an asynchronous messaging system, provided the sender and listener are guaranteed to be on the same machine, yes, you can do that. The sender would acquire the Mutex and then write to the resource, and once it’s done doing so, it will release the Mutex. The reader would similarly only access the resource after acquiring the Mutex—if the sender currently owns it, the thread will be blocked until the sender releases the Mutex.
Great. Thank you. 🙏🏽
No problem!