I have the following code (extracted from real code)
public static class AssemblyLogger {
public static Lazy<Window> Window { get; } = new Lazy<Window>(NewWindowHandler);
public static IScheduler Scheduler =>
new DispatcherScheduler( Window.Value.Dispatcher );
}
When I call Scheduler
, I get a NullReferenceException
. Stopping with the debugger, I see
As far as I know, this should be impossible. Window
it is statically initialized and read-only, and therefore any access to it should be available only and it should never be null.
I set a breakpoint against the initializer, but it never hits
I also tried readonly static field and still the same problem
public static readonly Lazy<Window> Window = new Lazy<Window>(NewWindowHandler);
Is it possible to have a race condition against static initialization?
MCVE . . MCVE : ( . - , .
public class Tester
{
public static class AssemblyLoggerMCVE
{
public static Lazy<Window> Window { get; } = new Lazy<Window>(NewWindowHandler);
private static Window NewWindowHandler() => new Window();
public static IScheduler Scheduler =>
new DispatcherScheduler(Window.Value.Dispatcher);
}
[StaFact]
public void AssemblyLoggerMCVEShouldWork()
{
AssemblyLoggerMCVE.Scheduler.Should().NotBeNull();
}
[StaFact]
public void AssemblyLoggerShouldWork()
{
AssemblyLogger.Scheduler.Should().NotBeNull();
}
}