Saturday 31 August 2013

C# event listener using lock() still throws exceptions

C# event listener using lock() still throws exceptions

im making an xna game, the problem involves the following classes:
Game class - this class listens to the event listeners of the two classes
below
Player class - this class launches a Fire() event, telling the game that
the player fires a bullet
Bullet class - this class launches a SelfDestruct() event(after a certain
traveled distance), telling the game that the instance has to be removed

The game class has a list of bullets, in the update method it does a
foreach on this list
The event listener for Fire() adds a new bullet to the bullet list The
event listener for SelfDestruct() removes the sender from the list(by
casting to bullet)
both events, as well as the update method locks the list for thread
safety. but it still throws an exception, telling that the list was
modified during the foreach.
how do i solve this; since i do lock on the list.. but that doesnt work:
Update:
public void Update(GameTime gameTime)
{
player.Update(GameTime gameTime);//can throw fire event
lock(Bullets)//Lock the list for thread safett
{
foreach(Bullet b in Bullets)//Throws exception when bullet is
added/removed
b.Update(gameTime);//can throw selfdestruct event
}
}
Fire listener:
void listen_fire(object sender, EventArgs e)
{
Player p = (Player)sender;/used to get coordinates and rotation stored
in the player
lock(Bullets)
{
Bullets.Add(new Bullet(p.Position,p.Rotation));
}
}
Self destruct listener:
void listen_selfdestruct(object sender, EventArgs e)
{
lock(Bullets)
{
Bullets.Remove((Bullet)sender);
}
}
I figured that this solution may fail because the event is thrown inside a
thread that has the list locked by itself already
any solutions are welcome, thanks for reading my question

No comments:

Post a Comment