All rules
CA2002Reliability Enabled by default: No

Do not lock on objects with weak identity

Do not lock on objects with weak identity

Microsoft docs

Description

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:

  • System.String
  • Arrays of value types, including integral types, floating-point types, and System.Boolean.
  • System.MarshalByRefObject
  • System.ExecutionEngineException
  • System.OutOfMemoryException
  • System.StackOverflowException
  • System.Reflection.MemberInfo
  • System.Reflection.ParameterInfo
  • System.Threading.Thread
  • this or Me object

Cause

A thread attempts to acquire a lock on an object that has a weak identity.

How to fix violations

To fix a violation of this rule, use an object from a type that is not in the list in the Description section.

Example

#pragma warning disable CA2002
// The code that's violating the rule is on this line.
#pragma warning restore CA2002

When to suppress

It is safe to suppress the warning if the locked object is this or Me and the visibility of the self object type is private or internal, and the instance is not accessible using any public reference.

Otherwise, do not suppress a warning from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0