Queue locking strategy error in Client Socket
The queue locking strategy is incorrect for the SocketContext.cs(68-70) call to
if (datagramQueue.Count > 0) { packet = datagramQueue.Dequeue();
In a highly concurrent environment, the queue isn't being locked for the entire transaction and a thread can pull an item off the queue making an empty queue when the datagram dequeue is called and causing a System.InvalidOperationException.
Maybe you should try to convert this to a CAS style operation or move the storage to a tested concurrent data structure.
I changed your DatagramQueue to read as follows
public bool TryDequeue(out Datagram datagram)
{
lock (queue_mutex){
if (datagramQueue.Count > 0)
{
datagram = datagramQueue.Dequeue();
return true;
}
}
datagram = new Datagram();
return false;
}
The enqueue call in the Pump() should also be updated to use the Enqueue method inside the class and not directly on the queue.
The bonus of TryDequeue is that it simplifies the calls in the SocketContext as follows
public bool Read(out Datagram packet)
{
return datagramQueue.TryDequeue(out packet);
}