Reworks dequeueing and CCriticalSection usage to ensure proper threading behavoir.

This commit is contained in:
Neil Dorin
2019-04-24 11:16:57 -06:00
parent 54324d7e43
commit 47b0399e3a

View File

@@ -199,35 +199,38 @@ namespace PepperDash.Core
Debug.Console(2, this, "textHandler is null"); Debug.Console(2, this, "textHandler is null");
} }
server.ReceiveDataAsync(Receive); server.ReceiveDataAsync(Receive);
CrestronInvoke.BeginInvoke(DequeueEvent);
var gotLock = DequeueLock.TryEnter();
if (gotLock)
CrestronInvoke.BeginInvoke((o) => DequeueEvent());
} }
void DequeueEvent(object notUsed) /// <summary>
/// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently.
/// It will dequeue items as they are enqueued automatically.
/// </summary>
void DequeueEvent()
{ {
try try
{ {
// Add CCritical Section while (true)
DequeueLock.TryEnter(); {
while (!MessageQueue.IsEmpty) // Pull from Queue and fire an event. Block indefinitely until an item can be removed, similar to a Gather.
{ var message = MessageQueue.Dequeue();
// Pull from Queue and fire an event. var dataRecivedExtra = DataRecievedExtra;
var Message = MessageQueue.TryToDequeue(); if (dataRecivedExtra != null)
var dataRecivedExtra = DataRecievedExtra; {
if (dataRecivedExtra != null) dataRecivedExtra(this, message);
{ }
dataRecivedExtra(this, Message); }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
Debug.Console(0, "GenericUdpServer DequeueEvent error: {0}\r", e); Debug.Console(0, "GenericUdpServer DequeueEvent error: {0}\r", e);
} }
finally finally
{ {
// Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it.
DequeueLock.Leave(); DequeueLock.Leave();
} }
} }
@@ -255,8 +258,6 @@ namespace PepperDash.Core
Server.SendData(bytes, bytes.Length); Server.SendData(bytes, bytes.Length);
} }
} }
public class GenericUdpReceiveTextExtraArgs : EventArgs public class GenericUdpReceiveTextExtraArgs : EventArgs