Skip to content

RangeAttribute throws InvalidCastException when accessed from multiple threads #1143

Closed
@bucolucas

Description

@bucolucas

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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions