Lock statement existed in C# from the very beginning. I still remember the first example.
lock (typeof(ClassName)) {
// do something
}
Those who use C# will immediatelly yell how perilous locking on the typeof is. But hey, I am just posting an official Microsoft’s advice here.
Of course, Microsoft did correct their example (albeit it took them a while) to now common (and correct) pattern.
private object SyncRoot = new object();
…
lock (SyncRoot) {
// do something
}
One curiosity of C# as a language is that you get to lock on any object. And here we just, as a convention, use the simplest object there is.
And yes, you can improve a bit on this if you use later .NET versions.
private readonly object SyncRoot = new();
…
lock (SyncRoot) {
// do something
}
However, if you are using C# 9 or later, you can do one better.
private readonly Lock SyncRoot = new();
…
lock (SyncRoot) {
// do something
}
What’s better there? Well, for starters we now have a dedicated object type. Combine that with a code analysis and now compiler can give you a warning if you make a typo and lock onto something else by accident. And also, …, wait …, wait …, yep, that’s it. Performance in all of these cases (yes, I am exluding typeof
one) is literally the same.
As features go, this one is small and can be easily overlooked. It’s essentially just a syntatic sugar. An I can never refuse something that sweet.