Rule Definition
Applications, having threads that try to acquire a lock, on an object that has a weak identity, can have reliability issues. This is because the thread can be blocked by a second thread in a different application domain that has a lock on the same object. An object is said to have a weak identity when it can be directly accessed across application domain boundaries. The following types have a weak identity and are flagged by the rule:
* MarshalByRefObject
* ExecutionEngineException
* OutOfMemoryException
* StackOverflowException
* String
* MemberInfo
* ParameterInfo
* Thread
Remediation
Try and avoid using weak identities.
Violation Code Sample
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) {}
}
}
Fixed Code Sample
using System; using System.IO; using System.Reflection; using System.Threading; namespace ReliabilityLibrary { class WeakIdentities { void LockOnWeakId2() { Object obj = new Object() MemoryStream stream = new MemoryStream(); lock(obj) {} } }
Reference
http://msdn.microsoft.com/en-us/library/ms182290.aspx
Related Technologies
.Net
Technical Criterion
Secure Coding - Time and State
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.