EDIT 11-20-2009: This question was posted quite some time ago, but the problem just crept up again this morning; so I'm hoping somebody else can provide some insight (though the answers provided already have been helpful).
Once in a blue moon in our production environment we get a NullReferenceException
from referencing the Items
property of a ListBox
control. I've included some example code below.
The parent form of the ListBox
in question holds a private Queue<string>
called QueuedMessages
. This queue receives new messages on events. On a timer that goes off every 500 ms, the following method gets executed:
void DisplayQueuedMessages() {
lock (QueuedMessages) {
while (QueuedMessages.Count > 0) {
string msg = QueuedMessages.Dequeue();
this.lbxMessages.Items.Insert(0, msg); // NullReferenceException
if (this.lbxMessages.Items.Count > MAX_LBX_ITEMS) {
this.lbxMessages.Items.RemoveAt(Me.lbxMessages.Items.Length - 1);
}
}
}
}
Again, as I've mentioned, this only throws NullReferenceException
very rarely. In several months of using the application it has happened three or four times.
Furthermore, the few times this has happened, it seems either the ListBox.Items
property or just the ListBox
itself is mysteriously gone for good: all subsequent methods that add items to the ListBox
throw exceptions. The only way to recover is to close the application and bring it back up.
Unfortunately, constantly distracted with a million other things to do, I never got around to adding logging before the insertions. I've added the logging now, but it could be a month or more before we see this problem again. In the meantime, any more ideas? What are some possible explanations for this?
I guess my real question is: Has anyone else ever seen this happen -- accessing a ListBox
that did exist and suddenly getting a NullReferenceException
-- and were you ever able to figure out why/how to fix the problem?