public async Task <bool> Send(string message, bool blockUntilSent = false)
        {
            // Queue the request.
            SendQueueItem item = new SendQueueItem()
            {
                Message = message
            };

            if (blockUntilSent)
            {
                item.Mutex = new SemaphoreSlim(0);
            }

            m_sendQueue.Add(item);

            if (blockUntilSent)
            {
                // Wait on the item to be sent.
                await item.Mutex.WaitAsync(c_sendWaitTimeoutMs);

                return(item.Sent);
            }

            return(true);
        }
        private async void SendThread()
        {
            while (State == SimpleWebySocketState.Connected)
            {
                // Wait on a message to send.
                SendQueueItem item = null;
                try
                {
                    item = m_sendQueue.Take(m_cancelToken.Token);
                }
                catch (Exception)
                {
                    // This throws when the cancel token if fired.
                    break;
                }

                // Grab the web socket locally for thread safety.
                ClientWebSocket ws = m_ws;
                if (ws == null)
                {
                    item.Mutex?.Release();
                    break;
                }

                if (m_sendQueue.Count > 50)
                {
                    Logger.Error($"Web socket send queue is looonnnggg {m_sendQueue.Count}.");
                }

                DateTime sendStart = DateTime.Now;

                // Send the message.
                try
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(item.Message);
                    await ws.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, m_cancelToken.Token);
                }
                catch (Exception)
                {
                    // If we failed to send, kill the connection.
                    await InternalDisconnect(WebSocketCloseStatus.NormalClosure);

                    item.Mutex?.Release();
                    break;
                }

                // Indicate the message was sent.
                item.Sent = true;
                item.Mutex?.Release();

                double sleepyTimeMs = MinTimeBetweenSends.TotalMilliseconds - (DateTime.Now - sendStart).TotalMilliseconds;
                if (sleepyTimeMs > 0)
                {
                    Thread.Sleep((int)sleepyTimeMs);
                }
            }
        }