Why is my initialized static property null when accessing it?

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

enter image description here

As far as I know, this should be impossible. Windowit 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

enter image description here

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);

    }

    /// This passes
    [StaFact]
    public void AssemblyLoggerMCVEShouldWork()
    {
        AssemblyLoggerMCVE.Scheduler.Should().NotBeNull();

    }

    /// This fails
    [StaFact]
    public void AssemblyLoggerShouldWork()
    {
        AssemblyLogger.Scheduler.Should().NotBeNull();

    }
}
+4
1

, , .

public class Tester
{
    public class AssemblyLoggerControlModel
    {
        public static IScheduler S = AssemblyLoggerMCVE.Scheduler;
    }

    public class AssemblyLogger
    {

        public static AssemblyLoggerControlModel ModelInstance { get; } = 
            new AssemblyLoggerControlModel();

        public static readonly Lazy<Window> Window =
            new Lazy<Window>(NewWindowHandler);

        private static Window NewWindowHandler() => new Window();

        public static IScheduler Scheduler => 
            new DispatcherScheduler(Window.Value.Dispatcher);

    }


}

. AssemblyLogger.ModelInstance AssemblyLoggerControlModel.S, AssemblyLogger.Scheduler, , , Window, , AssemblyLogger , - .

- ,

enter image description here

+1

Source: https://habr.com/ru/post/1688886/


All Articles