Tuesday, January 19, 2010

Silverlight DataAnnotations.Validator is not thread safe

 

I got this exception when using the Validator class with Silverlight. And yes, there is a property called ‘AProperty’ on the instance being validated :)

The type 'ClassWithValidatedProperty' does not contain a public property named 'AProperty'.
Parameter name: propertyName

at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.GetPropertyStoreItem(String propertyName)
at System.ComponentModel.DataAnnotations.ValidationAttributeStore.GetPropertyType(ValidationContext validationContext)
at System.ComponentModel.DataAnnotations.Validator.ValidateProperty(Object value, ValidationContext validationContext)
at SilverlightValidationRepro.ClassWithValidatedProperty.set_AProperty(String value)
at SilverlightValidationRepro.ValidatorNotThreadSafeReproduction.<Should_be_able_to_validate_concurrently>b__1()

The exception occured only once in a while, so we suspected threading issues. However, the MSDN docs say that Any public static (Shared in Visual Basic) members of this type are thread safe. Then take a look at the following test. It reproduces with the exception above, effectively proving a concurrency bug.

TheTest

Now take a look at the following screen shot from reflector. Can you spot the threading bug? Hint: the ‘return false’ should not happen in our case.

ValidatorThreading

Oh, and the workaround is to not consider the Validator class thread safe. We dispatch the code to a single thread. Another workaround would be to ensure that the Validator is finished with its initialization phase before unleasing multiple threads on it.