| Start |
|---|
| Throwing exception in a lock statement Following code will release the lock. There will be no problem. Behind the scenes lock statement works as More can be seen in the C# 5.0 Specification (opens new window): A where except that |
| Simple usage Common usage of In the following example If a thread reaches Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances. |
| Return in a lock statement Following code will release lock. For a detailed explanation, this SO answer (opens new window) is recommended. |
Anti-Patterns and gotchas Locking on an stack-allocated / local variableOne of the fallacies while using Assuming that locking restricts access to the synchronizing object itselfIf one thread calls: Expecting subclasses to know when to lockSometimes base classes are designed such that their subclasses are required to use a lock when accessing certain protected fields: It is much safer to encapsulate locking by using a Template Method (opens new window): Locking on a boxed ValueType variable does not synchronizeIn the following example, a private variable is implicitly boxed as it's supplied as an Boxing occurs in the It does not mean that a boxed ValueType can't be used for monitor locking at all: Now boxing occurs in constructor, which is fine for locking: Using locks unnecessarily when a safer alternative existsA very common pattern is to use a private If there are multiple methods accessing the By using a Using concurrent collections also improves performance because all of them employ lock-free techniques (opens new window) to some extent. |
| Using instances of Object for lock When using C#'s inbuilt NB. instances of Syntax
RemarksUsing the MSDN The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released. Best practice is to define a **private** object to lock on, or a private static object variable to protect data common to all instances. In C# 5.0 and later, the For C# 4.0 and earlier, the |
Read Article
https://develop.horje.com/learn/1434/reference