예제 #1
0
        public async Task ProcessQueue()
        {
            try
            {
                //await ReceiveSemaphore.WaitAsync();
                await ProcessingSemaphore.WaitAsync();

                if (_receiveQueue == null)
                {
                    return;
                }
                List <string> ids = new List <string>();
                for (var i = 0; i < _receiveQueue.Count; i++)
                {
                    if (_receiveQueue[i] != null)
                    {
                        string id = _receiveQueue[i].id;
                        if (!ids.Contains(id))
                        {
                            ids.Add(id);
                        }
                    }
                }
                // ids = (from m in _receiveQueue group m by new { m.id } into mygroup select mygroup.Key.id).ToList();
                foreach (var id in ids)
                {
                    SocketMessage        first = null;
                    List <SocketMessage> msgs  = null;
                    lock (_receiveQueue)
                    {
                        first = _receiveQueue.ToList().Where((x) => x.id == id).First();
                        msgs  = _receiveQueue.ToList().Where((x) => x.id == id).ToList();
                    }
                    if (first.count == msgs.Count)
                    {
                        string data = "";
                        foreach (var m in msgs.OrderBy((y) => y.index))
                        {
                            data += m.data;
                        }
                        var result = new Message(first, data);
                        Process(result);
                        foreach (var m in msgs.OrderBy((y) => y.index).ToList())
                        {
                            _receiveQueue.Remove(m);
                        }
                    }
                }
            }
            finally
            {
                //ReceiveSemaphore.Release();
            }

            try
            {
                List <SocketMessage> templist;
                lock (_sendQueue)
                {
                    templist = _sendQueue.ToList();
                }
                // await SendSemaphore.WaitAsync();
                foreach (var msg in templist)
                {
                    if (await SendString(JsonConvert.SerializeObject(msg), src.Token))
                    {
                        _sendQueue.Remove(msg);
                    }
                }
            }
            finally
            {
                //SendSemaphore.Release();
                ProcessingSemaphore.Release();
            }
        }