Join Nostr
2026-10-16 09:38:04 UTC

codementor on Nostr: Learn: Mutex A Mutex is a lock that can also work across processes when you give it a ...

Learn: Mutex

A Mutex is a lock that can also work across processes when you give it a name. Example: allow only one copy of your app to run.
It has thread affinity (it belongs to one thread): only the thread that took it can release it.

```csharp
var m = new Mutex();
m.WaitOne();
var t = new Thread(() =>
{
try { m.ReleaseMutex(); } catch (ApplicationException) { Console.WriteLine("only the owner can release"); }
});
t.Start(); t.Join();
m.ReleaseMutex();
```

It prints only the owner can release. Don't hold a Mutex across await: the code after it may run on another thread, which can't release it. Without a name, use lock instead: it is much faster.

Read more: https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives

#tip · TIP-076