Here is a class that, when compiled with Microsoft's minimum recommended code analysis rules, causes this warning:
CA2002 : Microsoft.Reliability : 'TestClass.SomeProperty.get()' locks on a reference of type 'string[]'. Replace this with a lock against an object with strong-identity.
public sealed class TestClass
{
public TestClass(string[] first, string[] second)
{
combinedStrings = Combined(first, second);
}
public string SomeProperty
{
get
{
lock (combinedStrings)
return "A string";
}
}
private readonly string[] combinedStrings;
private static string[] Combined(string[] first, string[] second)
{
var combined = new string[first.Length + second.Length];
first.CopyTo(combined, 0);
second.CopyTo(combined, first.Length);
return combined;
}
}
Why would a string array be considered a weak identity type? It's not like arrays get interned or something, do they? And even if they could be, I'm not locking on a statically defined one; it's dynamically constructed at run-time so guaranteed to be unique.
This is on Visual Studio 2010, if it makes a difference.
According to MSDN:
So the problem here is not the array, but the string type used. I would always opt to use an
object
as lock type. You can do that by creating a newobject
: