PhonicUK
PhonicUK

Reputation: 13854

NullReferenceException adding to a dictionary - very certain that nothing is null

Where Sessions is a Dictionary<Guid, WebSession>, and NewSession is new WebSession() I have this line:

Sessions.Add(NewSession.SessionID, NewSession);

Now at this point you're probably rolling your eyeballs and thinking "well either Sessions is null, or NewSession.SessionID is null." However:

Sessions == null
false
NewSession.SessionID == null
false
NewSession == null
false

It's pretty intermittent. Happens maybe one time in 50. And whenever it happens, I can just do Sessions.Add(NewSession.SessionID, NewSession); in the immediate window and it works fine.

The constructor for WebSession is synchronous, and Sessions is a vanilla dictionary with no added sugar.

I'm pretty sure I've done due diligence at this point. It's a harmless enough thing to happen in my application and it's trapped and handled cleanly - but I'm stumped as to what causes it in the first place.

Edit: I'm wondering if it's because my WebSession inherits : Dictionary<String, Object> but its constructor doesn't call base() - that still wouldn't explain it though since I can check that the object isn't null before doing Add(..)

Upvotes: 6

Views: 380

Answers (1)

to StackOverflow
to StackOverflow

Reputation: 124696

You need to use a thread-safe collection such as ConcurrentDictionary, or implement your own sychronization.

Attempting to access a Dictionary<TKey,TValue> from multiple threads can result in heisenbugs, which may well manifest themselves as a NullReferenceException.

Upvotes: 7

Related Questions