Join Nostr
2026-10-13 15:38:03 UTC

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