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,28 +199,30 @@ 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. // Pull from Queue and fire an event. Block indefinitely until an item can be removed, similar to a Gather.
var Message = MessageQueue.TryToDequeue(); var message = MessageQueue.Dequeue();
var dataRecivedExtra = DataRecievedExtra; var dataRecivedExtra = DataRecievedExtra;
if (dataRecivedExtra != null) if (dataRecivedExtra != null)
{ {
dataRecivedExtra(this, Message); dataRecivedExtra(this, message);
} }
} }
} }
catch (Exception e) catch (Exception e)
{ {
@@ -228,6 +230,7 @@ namespace PepperDash.Core
} }
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