public static async Task HandlePendingMessages(MessageStore <Tuple <string, byte[], WebSocketReceiveResult> > msgQueue, WebsocketStore <string, WebSocket> webSockets) { AutoResetEvent _taskWaitHandle = new AutoResetEvent(false); while (true) { if (msgQueue.Count > 0) { var item = msgQueue.Dequeue(); if (webSockets.Get(item.Item1, out var webSocket) && webSocket.State == WebSocketState.Open) { await webSocket.SendAsync(new ArraySegment <byte>(item.Item2, 0, item.Item3.Count), item.Item3.MessageType, item.Item3.EndOfMessage, CancellationToken.None); } else { msgQueue.Enqueue(item); } } else { _taskWaitHandle.WaitOne(1000); } } }