コード例 #1
0
        private async Task ProcessQueue(Stream stream)
        {
            while (true)
            {
                await Task.WhenAny(DataAvailableEvent.WaitOneAsync(), StopEvent.WaitOneAsync());

                if (!StopEvent.WaitOne(0))
                {
                    byte[] data;
                    if (!DataQueue.TryDequeue(out data))
                    {
                        Logger.Trace("Unable to deque element from Queue due to concurrency access");
                    }

                    if (DataQueue.IsEmpty)
                    {
                        Logger.Trace("Writing queue is empty. Wait for new element...");
                        DataAvailableEvent.Reset();
                    }

                    try
                    {
                        Logger.Trace("Write queue element {0}", data.GetHashCode());
                        await stream.WriteAsync(data, 0, data.Length);
                    }
                    catch (Exception e)
                    {
                        Logger.Debug(e, "Unable to send data");
                        QueueData(data);

                        break;
                    }
                }
                else
                {
                    Logger.Trace("Queue  is stopped");
                    StopEvent.Reset();
                    break;
                }
            }
        }
コード例 #2
0
        public async Task <T> Dequeue(TimeSpan?timeout = null)
        {
            if (!await WaitHandle.WaitOneAsync(timeout).ConfigureAwait(false))
            {
                throw new TimeoutException("Unable to dequeue element. Timeout has reached");
            }

            T value;

            if (!Queue.TryDequeue(out value))
            {
                return(await Dequeue(timeout));
            }

            if (Queue.IsEmpty)
            {
                DataAvailableEvent.Reset();
            }

            return(value);
        }