Can anyone help me explain how TimeProvider.Current
can become null in the following class?
public abstract class TimeProvider
{
private static TimeProvider current =
DefaultTimeProvider.Instance;
public static TimeProvider Current
{
get { return TimeProvider.current; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
TimeProvider.current = value;
}
}
public abstract DateTime UtcNow { get; }
public static void ResetToDefault()
{
TimeProvider.current = DefaultTimeProvider.Instance;
}
}
Observations
TimeProvider.Current
is null (NullReferenceException is thrown).TimeProvider.Current
.FWIW, here's the DefaultTimeProvider class as well:
public class DefaultTimeProvider : TimeProvider
{
private readonly static DefaultTimeProvider instance =
new DefaultTimeProvider();
private DefaultTimeProvider() { }
public override DateTime UtcNow
{
get { return DateTime.UtcNow; }
}
public static DefaultTimeProvider Instance
{
get { return DefaultTimeProvider.instance; }
}
}
I suspect that there's some subtle interplay going on with static initialization where the runtime is actually allowed to access TimeProvider.Current
before all static initialization has finished, but I can't quite put my finger on it.
Any help is appreciated.
FWIW I just threw
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
in the getter, and it consistently reports the same ID for all test cases in a test run, so the issue seems not related to threading.
Based solely on this code, Current
could be null
based on it being set to null
. This obviously isn't helpful to you.
Could you provide the code for the tests? If there's a test interdependence, it would be helpful for readers in order to provide any feedback.
In the mean time, possibly Jon Skeet's article on singletons might be helpful, since DefaultTimeProvider
is effectively acting as a singleton: http://csharpindepth.com/Articles/General/Singleton.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With