From 47b0399e3a5b5d8af5dc54a50d0deec3bc94130c Mon Sep 17 00:00:00 2001 From: Neil Dorin Date: Wed, 24 Apr 2019 11:16:57 -0600 Subject: [PATCH] Reworks dequeueing and CCriticalSection usage to ensure proper threading behavoir. --- .../Pepperdash Core/Comm/GenericUdpServer.cs | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/Pepperdash Core/Pepperdash Core/Comm/GenericUdpServer.cs b/Pepperdash Core/Pepperdash Core/Comm/GenericUdpServer.cs index aba628e..8d3e748 100644 --- a/Pepperdash Core/Pepperdash Core/Comm/GenericUdpServer.cs +++ b/Pepperdash Core/Pepperdash Core/Comm/GenericUdpServer.cs @@ -199,35 +199,38 @@ namespace PepperDash.Core Debug.Console(2, this, "textHandler is null"); } server.ReceiveDataAsync(Receive); - CrestronInvoke.BeginInvoke(DequeueEvent); + + var gotLock = DequeueLock.TryEnter(); + if (gotLock) + CrestronInvoke.BeginInvoke((o) => DequeueEvent()); } - void DequeueEvent(object notUsed) + /// + /// 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. + /// + void DequeueEvent() { try { - // Add CCritical Section - DequeueLock.TryEnter(); - while (!MessageQueue.IsEmpty) - { - // Pull from Queue and fire an event. - var Message = MessageQueue.TryToDequeue(); - var dataRecivedExtra = DataRecievedExtra; - if (dataRecivedExtra != null) - { - dataRecivedExtra(this, Message); - } - - - } - - } + while (true) + { + // Pull from Queue and fire an event. Block indefinitely until an item can be removed, similar to a Gather. + var message = MessageQueue.Dequeue(); + var dataRecivedExtra = DataRecievedExtra; + if (dataRecivedExtra != null) + { + dataRecivedExtra(this, message); + } + } + } catch (Exception e) { Debug.Console(0, "GenericUdpServer DequeueEvent error: {0}\r", e); } 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(); } } @@ -255,8 +258,6 @@ namespace PepperDash.Core Server.SendData(bytes, bytes.Length); } - - } public class GenericUdpReceiveTextExtraArgs : EventArgs