I am getting a null reference exception that comes from this code in a multi-threaded environment:
public static void GetLogger(string loggerName) {
Logger logger = ListOfLoggers.Find(delegate(Logger newLogger)
{
return newLogger.Name.Contains(loggerName);
});
if (logger == null) {
ListOfLoggers.Add(new Logger(loggerName));
}
}
In the code above:
ListOfLoggers
can be empty, but is never null as it is initialized as a static readonly variable.A null Logger object cannot be created (will cause a TypeInitializationException), so
ListOfLoggers
never contains a null Logger object.The only way to instantiate a Logger object is to provide an argument that gets set to the Logger object's Name property, so I also do not see how
newLogger.Name
can be null.
The faulting line of the stack trace is:
LogManager.<>c__DisplayClass1.<GetLogger>b__0(Logger newLogger)
and seems to suggest that the class generated by the compiler to hold the newLogger
local variable in the delegate closure is the one that throws the null reference exception.
This seems to only happen in a multi-threaded environment, and I never see the null reference when calling the code above with a single thread. How is this possible?