Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRangeException thrown in foreach loop

Tags:

c#

photon

I'm using the Photon server to run a multiplayer game, once in every 100+ games, the server stops responding to input -- looking at the log file I'm getting the following exception:

2013-07-30 12:31:24,918 [11] ERROR Lite.Room [(null)] - System.IndexOutOfRangeException: Index was outside the bounds of the array. at STSLib.Engine.handleInput(Hashtable input, Int32 playerId) in C:\Program Files (x86)\Photon\Photon src-server\STSServer\STSLib\Engine.cs:line 130

Looking at my code, my line 130 of my engine class is a foreach loop:

foreach (Player p in players)
{
    Queue playerQueue = new Queue();
    returnTable.Add(p.playerId, playerQueue);       
}

Where player is a class I made to represent (you guessed it!) players of the game, and players is an array of Players. returntable, is a hashtable of queues of hashtables of other data that I am sending to the clients, and I am just instantiating each key with an empty queue.

The foreach loop gets called, and works multiple times before the game gets broken in this scenario -- that is to say that this exception starts getting thrown in the middle of gameplay.

Can anyone explain how a foreach loop could ever throw an index out of bounds exception?

like image 674
Jeremy Kalas Avatar asked Sep 15 '25 18:09

Jeremy Kalas


1 Answers

It should not ... unless you use concurrency and the players variable is changed elsewhere while the loop is running.

Afaik it is not possible to change players within the loop (I think you will get a runtime error on that location, but not on the foreach loop).

like image 147
Michel Keijzers Avatar answered Sep 18 '25 09:09

Michel Keijzers