-
Notifications
You must be signed in to change notification settings - Fork 5.2k
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:
Lines 162 to 167 in 4f9ae42
| 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.
Lines 203 to 209 in 4f9ae42
| 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)