Description
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:
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.
Unable to cast object of type 'System.DateTime' to type 'System.String'
System.ComponentModel.DataAnnotations.RangeAttribute.SetupConversion()
System.ComponentModel.DataAnnotations.RangeAttribute.IsValid(Object value)