Collection was modified?!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michel Racicot

    Collection was modified?!

    When executing the following function, I get this error message:

    Collection was modified; enumeration operation may not execute.

    The only thing that can modify lstClients is when I add one in it and I'm
    sure that my listener isn't accepting another connection. As you can see,
    I even locked it!!! What is wrong?

    private void ReceiveMessage( )
    {
    byte[] Packet = new byte[PACKET_SIZE];
    string sValue;
    int nSize;

    while (Started)
    {
    lock (lstClients)
    {
    foreach (TcpClient Client in lstClients)
    {
    NetworkStream NetStream = Client.GetStrea m();

    nSize = NetStream.Read( Packet, 0, PACKET_SIZE);
    sValue = Encoding.ASCII. GetString(Packe t, 0, nSize);
    System.Windows. Forms.MessageBo x.Show(sValue);
    }
    }
    }
    }



  • Peter Duniho

    #2
    Re: Collection was modified?!

    On Fri, 22 Aug 2008 14:22:50 -0700, Michel Racicot <mracicot@hotma il.com>
    wrote:
    When executing the following function, I get this error message:
    >
    Collection was modified; enumeration operation may not execute.
    >
    The only thing that can modify lstClients is when I add one in it and I'm
    sure that my listener isn't accepting another connection. As you can
    see,
    I even locked it!!! What is wrong?
    Locking is a cooperative affair. That is, all that using the "lock()"
    statement does is ensure that while the code in the locked block is
    executing, no other code in a block that locks on the same object can
    execute. There's nothing to stop code from just not using the "lock)"
    statement and modifying the collection in an unsynchronized way.

    So, most likely that's just what you've got somewhere. Code that modifies
    the collection without use of the "lock()" statement. Find the code, add
    the "lock()" statement, and it should work.

    Pete

    Comment

    Working...