CA2002: Do not lock on objects with weak identity
Visual Studio 2010
TypeName | DoNotLockOnObjectsWithWeakIdentity |
CheckId | CA2002 |
Category | Microsoft.Reliability |
Breaking Change | Non-breaking |
An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. The following types have a weak identity and are flagged by the rule:
The following example shows some object locks that violate the rule.
using System; using System.IO; using System.Reflection; using System.Threading; namespace ReliabilityLibrary { class WeakIdentities { void LockOnWeakId1() { lock(typeof(WeakIdentities)) {} } void LockOnWeakId2() { MemoryStream stream = new MemoryStream(); lock(stream) {} } void LockOnWeakId3() { lock("string") {} } void LockOnWeakId4() { MemberInfo member = this.GetType().GetMember("LockOnWeakId1")[0]; lock(member) {} } void LockOnWeakId5() { OutOfMemoryException outOfMemory = new OutOfMemoryException(); lock(outOfMemory) {} } } }