0

There is a ConcurrentDirectory instance like below

readonly ConcurrentDictionary<string, SessionPayload> _map 
            = new ConcurrentDictionary<string, SessionPayload>(StringComparer.InvariantCultureIgnoreCase);

And there is a thread check all the instances every several minutes

SessionPayload[] sessions = _map.Values.ToArray();

foreach (SessionPayload session in sessions) // <-- NullReferenceException from this line
{
    //...
}

I don't understand why that line throws NullReferenceException. Isn't Values thread-safe?

Br

Mr.Wang from Next Door
  • 10,685
  • 10
  • 47
  • 76
  • There's [no code path](http://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,fe55c11912af21d2,references) in there that could return `null`. And if it did it would fail on the `.ToArray()` call. That's definitely weird. Are you sure you're not calling some broken version of `.ToArray()`? Besides, the `.ToArray()` call is not needed at all since you get a snapshot copy of the dictionary contents. – Lucas Trzesniewski Feb 22 '15 at 14:45
  • 1
    The simplest explanation is the obvious one, you added a *null* to the dictionary. You won't find out until you iterate it. Just add a null check to your code that adds an item. And keep in mind that ConcurrentDictionary being thread-safe does *not* mean that *your* code is automatically thread-safe as well. It certainly isn't, you have no guarantee that the SessionPayload object is thread-safe. And that it is still valid after you made the copy, it might not even be in the dictionary anymore. – Hans Passant Feb 22 '15 at 15:09
  • Not only does the problem not have anything to do with threading but also relevant code is missing so that you can never receive an answer. Feel free to edit and reopen. – usr Feb 22 '15 at 15:58

0 Answers0