dotnet / winforms

Windows Forms is a .NET UI framework for building Windows desktop applications.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Refactor `lock` on `object` usage to `System.Threading.Lock`

elachlan opened this issue · comments

In .NET9 there is the new System.Threading.Lock
https://learn.microsoft.com/en-us/dotnet/api/system.threading.lock?view=net-9.0

It is recommended to use the EnterScope method with a language construct that automatically disposes the returned Lock.Scope such as the C# using keyword, or to use the C# lock keyword, as these ensure that the lock is exited in exceptional cases. These patterns might also have performance benefits over using Enter/TryEnter and Exit. The following code fragment illustrates various patterns for entering and exiting a lock.

Refactor the object used for the lock to Lock where appropriate. The new Lock class when used with lock() will not use system.threading.monitor, but instead will use system.threading.lock.

Benchmarks in this blog post suggest a 25% performance improvement in lock operations:
https://steven-giesel.com/blogPost/4cf6d48a-ec9d-4c68-961c-31fd8d8c1340

There are some limitations, I think the team is best positioned to decide whats best here.

We won't make changes until C# takes the change to the lock keyword out of preview.
dotnet/csharplang#7104

@kirsan31 I saw you commented on the runtime issue. What are your thoughts on this?

@JeremyKuhne you might be able to shoot this down early.

One thing I am wondering is if the heavy usage of lock (this) is on purpose?

We can explore this when the feature leaves preview state.

@kirsan31 I saw you commented on the runtime issue. What are your thoughts on this?

My thots on this:

  1. Need to wait until release.
  2. Need a full sets of benchmarks (with all usage types):
    • Acquire / release without waiting. I hope this must be faster then current object lock :)
    • Long time waiting. Must be at least not worse then current :)
    • Short time waiting. Here the main question because of SpinWait using. In some cases we can get better performance but in some case much worse (many short waiters will eat cpu ) :(

So if acquire/release without waiting will be faster (it must) then we can feel free to replace object locking in those cases where waiting is rare. In other cases some analysis will be needed I think...

The code base locks a lot on this. Which usually isn't a good idea. I'd like this issue to review that as well.

I've raised an roslyn-analyzer rule over at: dotnet/roslyn-analyzers#7361

It would make changes like this easier.