Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RangeAttribute throws InvalidCastException when accessed from multiple threads #1143

Closed
bucolucas opened this issue Dec 24, 2019 · 5 comments

Comments

@bucolucas
Copy link

bucolucas commented Dec 24, 2019

This happens intermittently if you use RangeAttribute for date values:

[Range(typeof(Date), "1900-01-01", "2019-06-06 23:59:00")]
public DateTime CreatedOn { get; set; }

It is reproducible 100% of the time from a debugger.

Construct a RangeAttribute object:

var range = new RangeAttribute(typeof(DateTime), "1900-01-01", "2019-06-06 23:59:00");

Set a breakpoint at line 166 in RangeAttribute.cs:

private void SetupConversion()
{
if (Conversion == null)
{
object minimum = Minimum;
object maximum = Maximum;

Execute .IsValid() from two or more threads:

Parallel.For(0, 2, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (i) => { _ = range.IsValid(DateTime.Now); }

Freeze the first thread to hit RangeAttribute.cs line 166. Disable the breakpoint and allow the other thread to run. It will execute all of SetupConversion since Conversion is still null.

Once the second thread has completed validation, pause the debugger and unfreeze the first thread. An InvalidCastException will be thrown on line 207.

TypeConverter converter = TypeDescriptor.GetConverter(type);
IComparable min = (IComparable)(ParseLimitsInInvariantCulture
? converter.ConvertFromInvariantString((string)minimum)
: converter.ConvertFromString((string)minimum));
IComparable max = (IComparable)(ParseLimitsInInvariantCulture
? converter.ConvertFromInvariantString((string)maximum)
: converter.ConvertFromString((string)maximum));

Unable to cast object of type 'System.DateTime' to type 'System.String'

System.ComponentModel.DataAnnotations.RangeAttribute.SetupConversion()
System.ComponentModel.DataAnnotations.RangeAttribute.IsValid(Object value)

@Dotnet-GitSync-Bot Dotnet-GitSync-Bot added area-System.ComponentModel.DataAnnotations untriaged New issue has not been triaged by the area owner labels Dec 24, 2019
@svick
Copy link
Contributor

svick commented Dec 25, 2019

What makes you think that RangeAttribute is thread-safe? Or is there some specific reason why it should be thread-safe?

@bucolucas
Copy link
Author

bucolucas commented Dec 26, 2019

It's not thread safe, and I think it should be. The framework creates one instance of RangeAttribute for each property it's declared on, so if you have fifty instances of the following class:

public class Foo
{
    [RangeAttribute(typeof(DateTime), "2001-01-01", "2050-01-01")]
    public DateTime Bar { get; set; }
}

All instances of Foo.Bar share one instance of the RangeAttribute class.

The attributes are created per-type in a thread-safe manner, and stored in a Singleton collection:

private TypeStoreItem GetTypeStoreItem(Type type)
{
Debug.Assert(type != null);
lock (_typeStoreItems)
{
if (!_typeStoreItems.TryGetValue(type, out TypeStoreItem item))
{
// use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones
var attributes = CustomAttributeExtensions.GetCustomAttributes(type, true);
item = new TypeStoreItem(type, attributes);
_typeStoreItems[type] = item;

The only reason it isn't thread-safe is because the date casting logic is outside the constructor, which is executed thread-safely.

I think a null check->lock->null check would solve this:

if (Conversion == null)
{
    lock(arbitraryObject)
    {
        if (Conversion == null)
        {
            // Existing conversion code
        }
    {
}

This would only contest the lock if Conversion hasn't been set, and prevent the Conversion logic from executing twice.

@danmoseley
Copy link
Member

Thanks for the explanation. Are the other ValidationAttribute's already thread safe?

(I don't myself own this code)

@bucolucas
Copy link
Author

I checked the other ValidationAttribute classes, I didn't find anything concerning. This is the only one that is giving my organization issues.

@ajcvickers
Copy link
Member

This is not something we plan to change. Data annotations cannot run significant code in their constructors due to legacy compatibility, and making this thread safe in other ways would likely introduce locks or other sources of contention to the code.

@ajcvickers ajcvickers removed the untriaged New issue has not been triaged by the area owner label Jun 22, 2020
@ghost ghost locked as resolved and limited conversation to collaborators Dec 11, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants