New Rule for C# and VB.NET - Locks should be released!

Hi .NET folks

We’ve all felt the pain of deadlocks so now SonarSource has a new rule for C# and VB.NET that can detect when a resource has been locked and might not get released. It’s the first rule to benefit from our new Symbolic Analysis engine and we’re pretty excited about it. It’s been enabled in the default SonarWay profile so look out for new issues and let us know if you’re finding it useful. In future releases, as more rules use the new engine, you’ll see improved accuracy and better support for the latest language features.

The rule is available in SonarCloud today and will follow in SonarQube 9.5 and SonarLint soon.

Tom

1 Like

That is a nice addition. It might be worth to add another rule in this erea:

Non-compliant

private object lock = new object(); // Noncompliant {{lock objects should be read-only.}}

Compliant

private readonly object lock = new object();
3 Likes

Thanks Corniel :slight_smile:

Yes, that’s a great suggestion for a rule, we’ll see what we can do

Tom

It might also be possible to check if the lock should be static or not, but that is way less forward, so I’m not sure if you can prevent (too many) false positives.

Thank you @Corniel for this suggestion. I’ve captured the idea here:

We’re planning to specify some threading/locking rules as a follow-up to this S2222.

If I get the rule idea correctly, then S2933 would also raise in most of the cases. And this rule would raise for any field used by lock / SyncLock statement. Even (or especially) when it is used for writing operations. Is that correct?

1 Like

That rule will only trigger if the lock object is not re-assigned, which is good obviously. It will not detect if a lock object is abused for something else; the reason to require it to be read-only in the first place. If that is worth the hassle is not up to me. Therefor just as a suggestion.

Another related rule might be that a static lock object should never be decorated with [ThreadStatic].

1 Like