Async Sockets with Events (Issue with Lock Statement)

So I have a dll library for my network that dispatches events. Originally I would of liked to use the event to handle the packet on the main Unity Thread. But because the delegate runs on the same thread that calls it, that will be impossible because of unity’s non-thread-safe code.

Next, I tried the queue approach where I store the received packets into an Array List, and then in the Update function of some class, I check the packets and handle them like so:

c# pseudo code

void Update() {
lock(client.Packets){
     if(client.Packets.Count > 0)
     {
          foreach(Packet p in client.Packets)
          {
               Handle_Packet(p);
          }
     }
}}

The problem I am getting is an error that says the “ has changed” coming from the foreach statement. Can someone shed light on this error for me?

Also: If someone can show me a way to cross-thread events so that the called event CAN run on the main unity thread so I may access Unity functions when handling the packet.

ArrayLists are only threadafe if they are public static, instance variables are not thread safe as such its possible that your worker thread is feeding the list while you are with foreach in it (MSDN tells you normally which ones offer which kind of safety, though restricted to public static is rather normal)

Thanks Dreamora for your quick response. I have looked over that fact. I will let you know if I get it to work.