Skip to content

Static constructor broken (not always executed) #13036

Closed

Description

@weltkante

After porting a server which has been running on Desktop Framework and Mono for years I noticed crashes due to static fields staying NULL meaning the static constructor did not execute.

According to the documentation I expect static constructors to run before an instance of the class is constructed, i.e. when the instance constructor runs all static fields have been initialized. This is not the case with .NET Core, in the following scenario the static helper1 field is not initialized before the constructor.

While the static field itself is not accessed the static constructor has visible side effects. In my particular usage the constructor call done when initializing static fields will register the static instance globally. These registrations do not happen in .NET Core causing my server to crash because important logic is skipped.

Example code
using System;
using System.Runtime.CompilerServices;

namespace NetCoreStaticConstructorBug
{
    public static class Program
    {
        public static bool StaticConstructor1Executed = false;
        public static bool StaticConstructor2Executed = false;

        public static void Main(string[] args)
        {
            // outputs "False, False"
            Console.WriteLine($"{StaticConstructor1Executed}, {StaticConstructor2Executed}");

            var runner1 = new Runner1();
            var runner2 = new Runner2();

            // outputs "False, True" on Core, "True, True" on Desktop/Mono
            Console.WriteLine($"{StaticConstructor1Executed}, {StaticConstructor2Executed}");

            RuntimeHelpers.RunClassConstructor(typeof(Runner1).TypeHandle);
            RuntimeHelpers.RunClassConstructor(typeof(Runner2).TypeHandle);

            // outputs "True, True"
            Console.WriteLine($"{StaticConstructor1Executed}, {StaticConstructor2Executed}");
        }
    }

    public sealed class Runner1
    {
        private static Helper helper1 = new Helper();

        private sealed class Helper
        {
            public Helper()
            {
                // in my actual program the Helper instances are network protocol
                // handlers registering themselves globally with another singleton instance
                Program.StaticConstructor1Executed = true;
            }
        }

        public Runner1() { }
    }

    public sealed class Runner2
    {
        static Runner2()
        {
            Program.StaticConstructor2Executed = true;
        }

        public Runner2() { }
    }
}

Note that Runner2 executes the static constructor but Runner1 does not execute on Core Framework. Observed on .NET Core 2.1.507 and 2.2.300, works fine on Desktop and Mono.

Activity

  1. jkotas commented on Jul 6, 2019

    @jkotas
    Member

    static Helper helper1 = new Helper() in your example is before-field-init static constructor. The spec allows before-field-init constructors to run any time before the field is accessed. .NET Framework took full advantage of this flexibility. As a result, the exact timing of before-field-init static constructors in .NET Framework is unpredictable, depends on multiple factors. For example, if you compile your example with optimizations on, the timing in .NET Framework will change to the .NET Core one (see snippet below).

    We have changed the timing in .NET Core to be consistent and predictable. The before-field-init static constructors are always triggered by the first field access in .NET Core. The behavior you are seeing in .NET Core is expected. More details are in #4346

    E.g. .NET Framework behavior with optimizations on and off:

    C:\repro>csc /o- test.cs
    Microsoft (R) Visual C# Compiler version 3.2.0-beta4-19327-05 (82fffbc4)
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    C:\repro>test.exe
    False, False
    True, True
    True, True
    
    C:\repro>csc /o+ test.cs
    Microsoft (R) Visual C# Compiler version 3.2.0-beta4-19327-05 (82fffbc4)
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    C:\repro>test.exe
    False, False
    False, True
    True, True
    
  2. weltkante commented on Jul 6, 2019

    @weltkante
    ContributorAuthor

    Thanks for the explanation, if I understood this right adding a literal static constructor to those classes will reliably prevent this optimization?

  3. jkotas commented on Jul 6, 2019

    @jkotas
    Member

    I understood this right adding a literal static constructor to those classes will reliably prevent this optimization?

    Yes.

  4. transferred this issue fromdotnet/coreclron Jan 31, 2020
  5. ghost locked as resolved and limited conversation to collaborators on Dec 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions