From 6992dd4174346a980e59cc0ede44c6acdc3b2e2e Mon Sep 17 00:00:00 2001 From: Matthew Endsley Date: Thu, 4 Feb 2021 13:54:15 -0800 Subject: [PATCH] Flush outgoing packets before shutting closing socket This ensures we at least attempt to send out Disconnect packets to connected clients when shutting down. Prior to this the send thread would race the Dispose thread causing indeterminate behavior. Sometimes disconnect packets would be sent out, sometimes they wouldn't. --- .../ThreadLimitedUdpConnectionListener.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Hazel/FewerThreads/ThreadLimitedUdpConnectionListener.cs b/Hazel/FewerThreads/ThreadLimitedUdpConnectionListener.cs index 46a723a..84ac5a4 100644 --- a/Hazel/FewerThreads/ThreadLimitedUdpConnectionListener.cs +++ b/Hazel/FewerThreads/ThreadLimitedUdpConnectionListener.cs @@ -366,20 +366,25 @@ namespace Hazel.Udp.FewerThreads kvp.Value.Dispose(); } + bool wasActive = this.isActive; + this.isActive = false; + + // Flush outgoing packets + this.sendQueue?.CompleteAdding(); + if (wasActive) + { + this.sendThread.Join(); + } + try { this.socket.Shutdown(SocketShutdown.Both); } catch { } try { this.socket.Close(); } catch { } try { this.socket.Dispose(); } catch { } - bool wasActive = this.isActive; - this.isActive = false; - this.receiveQueue?.CompleteAdding(); - this.sendQueue?.CompleteAdding(); if (wasActive) { this.reliablePacketThread.Join(); - this.sendThread.Join(); this.receiveThread.Join(); this.processThreads.Join(); } @@ -388,7 +393,6 @@ namespace Hazel.Udp.FewerThreads this.receiveQueue = null; this.sendQueue?.Dispose(); this.sendQueue = null; - } public void Dispose() -- 2.39.5