While I’m working on parallelism of our framework, I’ve confronted a strange condition which I can’t imagine why! I simplified the situation to describe it easy.
consider this code:
foreach(var person in personList)
{
if (person.Name == "Mehran")
break;
}
which the personList is shared between multiple threads.
In what circumstances is it possible for person to be null and I get the NullReferenceException for person.Name?
As I know, the person is considered as a local variable here and if the we get into the foreach block, so we have iterated the personList successfully, so person should not be null in any circumstances or any parallel scenario.
Even if the personList is changed by another thread, or the referenced person is disposed, the person variable should have a value. Because no one has access to change where the person is referenced to.
Is it any scenario to explain the situation?
Just because you’re iterating over
personListsuccessfully doesn’t mean it doesn’t contain any null values. For example:(Additionally, if anything is modifying the list, you’re generally in trouble – they’re not thread-safe in the face of writers – but I don’t think that needs to be part of the problem.)