Zero Read-Only Lock Function

How does a static readonly object become null? (I set the _lock object as static, not static, but always read-only.)

The check method works correctly several times, and then after it is called 2-3 times, the _lock object is null. Is this an indicator that the castle belongs to another thread?

enter image description here

+4
source share
1 answer

In addition to reflection, another way can happen in which this (more precisely, the exclusion of a reference to a static variable assigned through the initializer) is if you have a static constructor defined elsewhere in your class that for some reason sets the value null for example:

class Program
{
    class A
    {
        private static readonly object _lock = new object();

        public void Validate()
        {
            lock (_lock) // NullReferenceException here...
            {
                Console.WriteLine("Not going to make it here...");
            }
        }

        static A()
        {
            Console.WriteLine(_lock.ToString());
            Console.WriteLine("Now you can see that _lock is set...");
            _lock = null;
        }
    }

    static void Main(string[] args)
    {
        var a = new A();
        a.Validate();
    }
}
-4

All Articles