I have a List<int> that I update on every Update() call by calling Add() to add another integer to that list
On every call to Draw(), I foreach on that List and use the stored int to draw something to the screen.
The problem I have is that the for the first few frames (i.e. few calls to Update), my List is out of sync. The stuff I added never shows up.
I added some tracing to file with this code:
log.WriteLine("start list with count " + Actions.Count);
int nextAction = getNextAction(); // right now this is just some additions
Actions.Add(nextAction);
movelog.WriteLine("end list with count " + Actions.Count);
I get this trace:
start list with count 0
end list with count 1
start list with count 0
end list with count 1
start list with count 0
end list with count 1
start list with count 0
end list with count 1
start list with count 0
end list with count 1
start list with count 1
end list with count 2
start list with count 2
end list with count 3
start list with count 3
end list with count 4
As you can see for the first few calls to this section of the code (i.e. calls to Update()), I add to the list and then the next time it’s called it’s magically gone as if nothing was added to the list. After the fifth time it finally works. This is pretty consistent across runs.
I tried locking on the list object, and I get the exact same behavior.
What is going on with my code? I’m stumped. I’m not doing anything in parallel and I tried tracing the ManagedThreadId every time I add to the list and the thread id is the same.
I’m guessing you’re removing items from the list in the Draw() call, that will give the effect you describe I think because XNA won’t be running 1 Update() method for each Draw() call.
XNA tries to run Update() 60 times a second by default but the Draw() method tries to run in sync with the monitor refresh rate and will be called less if the update method takes too long.
Edit
it seems I was wrong about the Draw() method removing items from the array, the next step I would try while looking for the root of this problem is to make sure nothing is acting on the list out of order would be to change it to a list that logs activities.