D
Daniel
Hi guys
In regards to the foreach and for loops. I am trying to avoid this
exception:exception:
"Collection was modified; enumeration operation may not execute.
System.InvalidOperationException"
The problem is i have a timer, that checks at an interval for any changes to
a list if there are changes it removes the corresponding item:
See below:
public override bool RemoveRoom(int roomId)
{
try
{
for (int i = 0; i < _roomList.Count; i++)
{
Room room = (Room)_roomList;
if (room.RoomId.Equals(roomId))
{
//clear timers
_timeManager.RemoveAll(roomId);
_roomList.RemoveAt(i);
return true;
}
}
return false;
}
catch(Exception e)
{
Console.WriteLine("Error removing room, exception: " +
e.Message + " " + e.GetType().ToString());
return false;
}
}
I understand why i am getting the error, i am changing the enumeratoed list
by removing an item durin the enumeration. So my question is, how do i do
this saftely?
Another issue i have is a render loop that runs in a for each liek this:
foreach(Object o in objList)
{
o.RenderObject();
}
And that runs all the time, but objects need to be removed from that list
when they are no longer 'alive'. Again how do i do that saftely?
Is the answer to lock it so that no other thread accesses it while the
object is removed? How would this hit efficiency is this even the right way
about it?
So to summarise, how do you remove an item from a list/array while it is
being looked through via a loop safetly? Thanks is advance
In regards to the foreach and for loops. I am trying to avoid this
exception:exception:
"Collection was modified; enumeration operation may not execute.
System.InvalidOperationException"
The problem is i have a timer, that checks at an interval for any changes to
a list if there are changes it removes the corresponding item:
See below:
public override bool RemoveRoom(int roomId)
{
try
{
for (int i = 0; i < _roomList.Count; i++)
{
Room room = (Room)_roomList;
if (room.RoomId.Equals(roomId))
{
//clear timers
_timeManager.RemoveAll(roomId);
_roomList.RemoveAt(i);
return true;
}
}
return false;
}
catch(Exception e)
{
Console.WriteLine("Error removing room, exception: " +
e.Message + " " + e.GetType().ToString());
return false;
}
}
I understand why i am getting the error, i am changing the enumeratoed list
by removing an item durin the enumeration. So my question is, how do i do
this saftely?
Another issue i have is a render loop that runs in a for each liek this:
foreach(Object o in objList)
{
o.RenderObject();
}
And that runs all the time, but objects need to be removed from that list
when they are no longer 'alive'. Again how do i do that saftely?
Is the answer to lock it so that no other thread accesses it while the
object is removed? How would this hit efficiency is this even the right way
about it?
So to summarise, how do you remove an item from a list/array while it is
being looked through via a loop safetly? Thanks is advance