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-16 09:38:04 UTCEvent JSON
{
"id": "f6f885a479d07944a399b0bf351dca226fecde3c1a0bcf8423cc15f8582281db",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792143484,
"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": "c22aa9f8632288cef8b612a9aa61c8e7961732b2869b7c4f48d0b42fae0d8e1c7f4130d67b6b00f181697d8b74ccd9e4e1e7aaa63e1fd1fee858e6f20e430243"
}