NullReferenceException at System.Collections.Generic.LinkedList`1.AddLast(T value)

c#, linked-list, multithreading, nullreferenceexception

Solution

This happens from multiple threads synchronized via locks.

I suspect you forgot to lock in one place, basically. Is that possible, or are you certain you only access it within a single place?

For example, I can see how you'd get that exception if you had one thread removing the final element in the list at the same time as another thread was adding a new element.

Rather than exposing the "raw" linked list, I suggest you try to only ever access it directly from a single class, which can take responsibility for all the locking (and which should be very, very simple).

Problem

I have a `LinkedList<T>` in my project where I add and remove a lot of elements (few hundred per second). This happens from multiple threads synchronized via locks. Now sometimes (maybe every few 100.000 elements) I get a `NullReferenceException` "inside" the `AddLast` method, so the top entry of the stack trace is as following: at System.Collections.Generic.LinkedList`1.AddLast(T value) Does someone have an idea why this could happen and how I can avoid this? A simple/stupid try->catch->repeat would be my best idea, but thats more a dirty workaround...

Original source