codementor on Nostr: Learn: The lock statement lock lets only one thread at a time run a block of code; ...
Learn: The lock statement
lock lets only one thread at a time run a block of code; the others wait.
```csharp
var sync = new object();
int total = 0;
Parallel.For(0, 1000, i => { lock (sync) total += i; });
Console.WriteLine(total);
```
It prints 499500 (0 + 1 + ... + 999) every time. On a plain object, lock is Monitor.Enter/Exit in a try/finally, so it is released even when an exception is thrown, and the same thread may enter it again (it is reentrant).
Rules: lock on a private object, never on this, a string or a type. Keep the block short. You can't await inside a lock.
Read more:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock#tip · TIP-074
Published at
2026-11-21 19:07:41 UTCEvent JSON
{
"id": "2a3ec3530ab892801fb960a01474c3041486fa80a235013a1e12107b69b4ec07",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1795288061,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: The lock statement\n\nlock lets only one thread at a time run a block of code; the others wait.\n\n```csharp\nvar sync = new object();\nint total = 0;\nParallel.For(0, 1000, i =\u003e { lock (sync) total += i; });\nConsole.WriteLine(total);\n```\n\nIt prints 499500 (0 + 1 + ... + 999) every time. On a plain object, lock is Monitor.Enter/Exit in a try/finally, so it is released even when an exception is thrown, and the same thread may enter it again (it is reentrant).\nRules: lock on a private object, never on this, a string or a type. Keep the block short. You can't await inside a lock.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock\n\n#tip · TIP-074",
"sig": "000504954a04e7bc377fa85e131f364e893f89413a2f10c79d6281b50733da63c7241cb7d191779273702e546b9b3ec14023b2f48254c885020ac37d081d9029"
}