How can a static readonly object become null? (I've set the _lock object as static and not static, but always readonly.)
The validate method works fine for a few times, then after it's called 2-3 times the _lock object is null. Is this an indicator that the lock is owned by another thread?
Besides reflection, another of the ways that this (more specifically, a null reference exception on a static variable assigned via initializer) can happen is if you have a static constructor defined elsewhere in your class that for some reason sets the value to null, eg:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.