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-10-13 15:38:03 UTCEvent JSON
{
"id": "7efae1650f60ec57bd35dcb941401398603d4648fabc95669ad830ef6fbd61c8",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1791905883,
"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": "bca975e343c6232c0c116a733fb3b84d9b516df55bd96bbd936bb117f39ca88f43991f397d27c47a6fceab6debcbcc13feb999d7ff04b84bdbf4bcad26105397"
}