Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:csharp-best-practices/locking-public-instances
Language: C#
Severity: Warning
Category: Performance
Description
The rule “Do not lock on publicly accessible instance” is a crucial guideline in multithreaded programming in C#. It is designed to prevent potential deadlocks and other synchronization issues that can occur when multiple threads try to acquire a lock on the same publicly accessible object.
Locking on a public object can lead to deadlocks if another thread outside your code also locks on that object. This is because locking on ’this’ or other publicly accessible instances exposes your lock to external manipulation and can cause unpredictable behavior.
How to remediate
To avoid this, always use a private, readonly object to lock on. This practice ensures that the lock is not accessible from outside the class and that its state can’t be modified, providing a controlled environment for synchronization. For example, you can create a private, readonly object specifically for locking like so: private readonly object _lockObject = new object();. Then, use this object in your lock statement: lock (_lockObject) {...}. This way, you adhere to encapsulation principles and maintain control over the synchronization process.