Menu

I Changed object to Lock and Stopped Paying the Monitor Tax
📰

I Changed object to Lock and Stopped Paying the Monitor Tax

DEV Community: dotnet·Sukhpinder Singh·25 days ago
#DJNW67Lj
#devtodotnet#devto#dev#lock#console
Long article (1831 words) — no AI summary yet.
Reading 0:00
15s threshold

I had a counter behind a lock that a profiler kept flagging, and I couldn't figure out why. The lock was basically never contended. One thread wrote to it almost all the time; the lock was there for the rare second writer that might show up. So I expected it to cost close to nothing. It didn't cost nothing. It cost about 24 nanoseconds every single acquire, and on a hot path that adds up to a line you can see in a flame graph.

The thing I'd stopped thinking about is what lock (someObject) actually compiles to. It's Monitor.Enter and Monitor.Exit wrapped in a try/finally, and Monitor hangs its state off the object's sync block. Even with no contention at all, you pay for that bookkeeping on every acquire and release. For years that was just the price of the lock keyword and there was nothing to do about it.

Since .NET 9 there is. There's a real type now, System.Threading.Lock , and the compiler special-cases it: if you lock on a variable whose type is Lock , it doesn't go through Monitor at all.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.