Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Development Edition
 Do not lock on objects with weak id...
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
Visual Studio Team System
Do not lock on objects with weak identity

Updated: November 2007

TypeName

DoNotLockOnObjectsWithWeakIdentity

CheckId

CA2002

Category

Microsoft.Reliability

Breaking Change

Non Breaking

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

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:

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

Do not suppress a warning from this rule.

The following example shows some object locks that violate the rule.

Visual Basic
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Threading

Namespace ReliabilityLibrary

   Class WeakIdentities

      Sub SyncLockOnWeakId1()

         SyncLock GetType(WeakIdentities)
         End SyncLock

      End Sub

      Sub SyncLockOnWeakId2() 

         Dim stream As New MemoryStream()
         SyncLock stream
         End SyncLock

      End Sub

      Sub SyncLockOnWeakId3() 

         SyncLock "string"
         End SyncLock

      End Sub

      Sub SyncLockOnWeakId4() 

         Dim member As MemberInfo = _
            Me.GetType().GetMember("SyncLockOnWeakId1")(0)
         SyncLock member
         End SyncLock

      End Sub

      Sub SyncLockOnWeakId5()

         Dim outOfMemory As New OutOfMemoryException()
         SyncLock outOfMemory
         End SyncLock

      End Sub

   End Class

End Namespace

C#
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) {}
      }
   }
}

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker