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
Published at
2026-10-25 17:37:55 UTCEvent JSON
{
"id": "f693a0ed6f1bf155c1ee320d4e5201b288244a6b04790f71c23f0946bbceaaad",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792949875,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Mutex\n\nA 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.\nIt has thread affinity (it belongs to one thread): only the thread that took it can release it.\n\n```csharp\nvar m = new Mutex();\nm.WaitOne();\nvar t = new Thread(() =\u003e\n{\n try { m.ReleaseMutex(); } catch (ApplicationException) { Console.WriteLine(\"only the owner can release\"); }\n});\nt.Start(); t.Join();\nm.ReleaseMutex();\n```\n\nIt 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.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives\n\n#tip · TIP-076",
"sig": "f7b797b734339b4ba8183a5592529d0434ddde321ec747474cc72d93000248c06a4963dcef528e8d4a839d6c9e9772eac52a2e50bdd1668efc0a4ca58522f74c"
}