Reputation: 103
I'm using an ObservableCollection
(_queue
) as a queue to show a stream of items. I have a non-async next
method with the following relevant code fragment:
if (_queue.Count > 0) {
try {
playingTrack = _queue[0];
_queue.RemoveAt(0);
}
catch (Exception e) {
Debug.WriteLine("Failed to remove first of queue size="+_queue.Count);
}
}
Note the (temporary) general catch which should not be necessary. I tend to catch the ArgumentOutOfRangeException
thrown by RemoveAt
seemingly at random, even though the index zero should be valid given the preceding condition and that the indexing succeeded. Even so, the debug message always shows up showing a size > 0. The exception has happened so far only when the above method was called by MediaElement.MediaEnded
all within the UI thread.
After reading up and down on msnd I still haven't found any documentation about this behavior. Does anybody have an idea of what could be happening here?
Upvotes: 2
Views: 2136
Reputation: 755219
The code in the question by itself could never cause this exception because it properly guards the access against the count. Hence the only explanation is that code not mentioned in the question is causing the exception to occur. The most likely cause is either
Given that this is an ObservableCollection<T>
my guess is #2 is the most likely. Essentially some code which is looking for a change in the collection is mistakenly accessing a value that is no longer valid. If this is the case that code will be at the very top of the stack when the exception is thrown.
Upvotes: 2