void ReceiveCallback(IAsyncResult result)
{
Monitor.Enter(callbackLock);
Byte[] bytes = null;
IPEndPoint remoteEP = null;
try
{
bytes = receivingUdpClient.EndReceive(result, ref remoteEP);
}
catch (ObjectDisposedException e)
{
// Ignore if disposed. This happens when closing the listener
}
// Process bytes
if (bytes != null && bytes.Length > 0)
{
if (BytePacketCallback != null)
{
BytePacketCallback(bytes);
}
else if (OscPacketCallback != null)
{
OscPacket packet = null;
try
{
packet = OscPacket.GetPacket(bytes, remoteEP);
}
catch (Exception e)
{
// If there is an error reading the packet, null is sent to the callback
}
OscPacketCallback(packet);
}
else
{
lock (queue)
{
queue.Enqueue(bytes);
}
}
}
if (closing)
{
ClosingEvent.Set();
}
else
{
// Setup next async event
AsyncCallback callBack = new AsyncCallback(ReceiveCallback);
receivingUdpClient.BeginReceive(callBack, remoteEP);
}
Monitor.Exit(callbackLock);
}