public void OutputAvailableAsync_NoItemsInQueue_IsNotCompleted()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();

                var task = queue.OutputAvailableAsync();

                await AssertEx.NeverCompletesAsync(task);
            });
        }
Пример #2
0
        //如果平台不支持TPL数据流库,可以使用Nito.AsyncEx中的AsyncProducerConsumerQueue<T>类,它同时也支持同步和异步方法。
        async void Example17()
        {
            AsyncProducerConsumerQueue <int> queue = new AsyncProducerConsumerQueue <int>();
            //异步的生产者代码
            await queue.EnqueueAsync(7);

            await queue.EnqueueAsync(13);

            //同步的生产者代码
            queue.Enqueue(7);
            queue.Enqueue(13);
            queue.CompleteAdding();
            //单个消费者时的异步代码
            while (await queue.OutputAvailableAsync())
            {
                Trace.WriteLine(await queue.DequeueAsync());
            }
            //多个消费者时的异步代码
            while (true)
            {
                //var result = await queue.TryDequeueAsync();
                //if (result.Success) break;
                //Trace.WriteLine(result.Item);
            }
            //同步的消费者代码
            foreach (var item in queue.GetConsumingEnumerable())
            {
                Trace.WriteLine(item);
            }
        }
Пример #3
0
        //不支持TPL数据流时使用Nito.AsyncEx中的AsyncProduceConsumerQueue<T>类。
        async void Example12()
        {
            AsyncProducerConsumerQueue <int> _asyncQueue = new AsyncProducerConsumerQueue <int>();
            //生存者代码
            await _asyncQueue.EnqueueAsync(7);

            await _asyncQueue.EnqueueAsync(13);

            _asyncQueue.CompleteAdding();
            //消费者代码
            //先显示“7”,后显示“13”。
            while (await _asyncQueue.OutputAvailableAsync())
            {
                Trace.WriteLine(await _asyncQueue.DequeueAsync());
            }

            //AsyncProducerConsumerQueue<T>具有限流功能,如果生存者的运行速度可能比消费者快,这个功能就是必需的。
            AsyncProducerConsumerQueue <int> _asyncQueue2 = new AsyncProducerConsumerQueue <int>(maxCount: 1);
            //单个消费者
            await _asyncQueue2.EnqueueAsync(7);  //这个添加过程会立即执行

            await _asyncQueue2.EnqueueAsync(13); //这个添加过程会(异步地)等待,直到7被移除,然后才会加入13。

            _asyncQueue2.CompleteAdding();
            //多个消费者
            while (true)
            {
                //var dequeueResult = await _asyncQueue.TryDequeueAsync();
                //if (dequeueResult.Success) break;
                //Trace.WriteLine(dequeueResult.Item);
            }
        }
 public PowerShellContextTests()
 {
     this.powerShellContext = new PowerShellContext();
     this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
     this.powerShellContext.OutputWritten += OnOutputWritten;
     this.stateChangeQueue = new AsyncProducerConsumerQueue<SessionStateChangedEventArgs>();
 }
Пример #5
0
        async Task <ConsumerResponse> HandleConsumerRequest(
            SubscriptionId subscriptionId,
            AsyncProducerConsumerQueue <StreamEvent> queue,
            ConsumerRequest request,
            CancellationToken cancellationToken)
        {
            try
            {
                var eventHorizonEvent = request.Event;
                await queue.EnqueueAsync(
                    new StreamEvent(
                        eventHorizonEvent.Event.ToCommittedEvent(),
                        eventHorizonEvent.StreamSequenceNumber,
                        StreamId.EventLog,
                        Guid.Empty,
                        false),
                    cancellationToken).ConfigureAwait(false);

                return(new ConsumerResponse());
            }
            catch (Exception ex)
            {
                _logger.Warning(ex, "An error occurred while handling event horizon event coming from subscription {Subscription}", subscriptionId);
                return(new ConsumerResponse
                {
                    Failure = new Failure(FailureId.Other, $"An error occurred while handling event horizon event coming from subscription {subscriptionId}. {ex.Message}")
                });
            }
        }
Пример #6
0
 static void Main(string[] args)
 {
     _asyncProducerConsumerQueue = new AsyncProducerConsumerQueue <string>(ProcessUdpData);
     Console.WriteLine("Starting Udp listening");
     ReceivePacketsAsync();
     Console.Read();
 }
Пример #7
0
 public static async Task EnqueueRangeAsync <T>(this AsyncProducerConsumerQueue <T> queue, IEnumerable <T> items, CancellationToken cancellationToken)
 {
     foreach (var item in items)
     {
         await queue.EnqueueAsync(item, cancellationToken).ConfigureAwait(false);
     }
 }
        public void RemainingProcessingTimeShouldBeReported()
        {
            var actionCounter = 0;

            void TestAction(int x)
            {
                Thread.Sleep(x);
                actionCounter += 1;
            }

            var sut = new AsyncProducerConsumerQueue <int>(TestAction);

            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);

            Thread.Sleep(100);
            Assert.That(sut.EstimatedCurrentCompletionTimeMs, Is.InRange(200, 1000));
            Thread.Sleep(1000);

            Assert.That(actionCounter, Is.EqualTo(6));
            Assert.That(sut.TotalJobsCompleted, Is.EqualTo(6));
            Assert.That(sut.LastJobTimeTakenMs, Is.InRange(45, 100));
            Assert.That(sut.RollingAverageTimeMs, Is.InRange(45, 120));
            Assert.That(sut.EstimatedCurrentCompletionTimeMs, Is.EqualTo(0));

            sut.Dispose();
        }
        public void WaitForProcessingCompletionWithCancellationShouldCancel()
        {
            var actionCounter = 0;

            void TestAction(int x)
            {
                Thread.Sleep(x);
                actionCounter += 1;
            }

            var sut = new AsyncProducerConsumerQueue <int>(TestAction);

            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);
            sut.ProduceJob(50);

            sut.WaitForProcessingCompletion(100, true);

            Assert.That(actionCounter, Is.InRange(3, 5));
            Assert.That(sut.TotalJobsCompleted, Is.InRange(3, 5));

            sut.Dispose();
        }
        public void StatsShouldBeCorrectAfterWaitForProcessingCompletionRun()
        {
            var actionCounter = 0;

            void TestAction(int x)
            {
                Thread.Sleep(x);
                actionCounter += 1;
            }

            var sut = new AsyncProducerConsumerQueue <int>(TestAction);

            sut.ProduceJob(1500);
            sut.ProduceJob(50);

            sut.WaitForProcessingCompletion();

            Assert.That(actionCounter, Is.EqualTo(2));
            Assert.That(sut.TotalJobsCompleted, Is.EqualTo(2));
            Assert.That(sut.LastJobTimeTakenMs, Is.InRange(50, 80));
            Assert.That(sut.RollingAverageTimeMs, Is.InRange(750, 850));
            Assert.That(sut.EstimatedCurrentCompletionTimeMs, Is.EqualTo(0));

            sut.Dispose();
        }
 public PowerShellContextTests()
 {
     this.powerShellContext = new PowerShellContext();
     this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
     this.powerShellContext.OutputWritten       += OnOutputWritten;
     this.stateChangeQueue = new AsyncProducerConsumerQueue <SessionStateChangedEventArgs>();
 }
Пример #12
0
 public ControlTimer(Func <TimeSpan> timerFactory)
 {
     this.timerFactory = timerFactory;
     TickCh            = new AsyncProducerConsumerQueue <bool>();
     ResetCh           = new AsyncProducerConsumerQueue <bool>();
     StopCh            = new AsyncProducerConsumerQueue <bool>();
 }
Пример #13
0
    async Task Test()
    {
        var _asyncQueue = new AsyncProducerConsumerQueue <int>();

        // Producer code
        await _asyncQueue.EnqueueAsync(7);

        await _asyncQueue.EnqueueAsync(13);

        _asyncQueue.CompleteAdding();

        // Consumer code
        // Displays "7" followed by "13".
        while (await _asyncQueue.OutputAvailableAsync())
        {
            Trace.WriteLine(await _asyncQueue.DequeueAsync());
        }



        while (true)
        {
            int item;
            try
            {
                item = await _asyncQueue.DequeueAsync();
            }
            catch (InvalidOperationException)
            {
                break;
            }
            Trace.WriteLine(item);
        }
    }
        public void GetEnumerator_ItemsInQueue_ReturnsItems()
        {
            var queue = new AsyncProducerConsumerQueue <int>(new[] { 1, 2, 3 });
            var seq   = queue as IEnumerable <int>;

            Assert.That(seq, Is.EqualTo(new[] { 1, 2, 3 }));
        }
Пример #15
0
    async Task <ConsumerResponse> HandleEventFromEventHorizon(
        AsyncProducerConsumerQueue <StreamEvent> connectionToStreamProcessorQueue,
        EventHorizonEvent @event,
        CancellationToken cancellationToken)
    {
        try
        {
            _metrics.IncrementTotalEventHorizonEventsHandled();
            _logger.HandlingEventForSubscription(_subscriptionId);
            var streamEvent = new StreamEvent(
                @event.Event.ToCommittedEvent(),
                @event.StreamSequenceNumber,
                StreamId.EventLog,
                PartitionId.None,
                false);

            await connectionToStreamProcessorQueue.EnqueueAsync(streamEvent, cancellationToken).ConfigureAwait(false);

            return(CreateSuccessfulResponse());
        }
        catch (Exception exception)
        {
            _metrics.IncrementTotalEventHorizonEventsFailedHandling();
            _logger.ErrorWhileHandlingEventFromSubscription(_subscriptionId, exception);
            return(CreateFailureResponse(new Failure(
                                             SubscriptionFailures.ErrorHandlingEvent,
                                             exception.Message)));
        }
    }
        public void GetEnumerator_NoItemsInQueue_ReturnsEmptySeq()
        {
            var queue = new AsyncProducerConsumerQueue <int>();
            var seq   = queue as IEnumerable <int>;

            Assert.That(seq.Count(), Is.EqualTo(0));
        }
        public void IsCompleted_AfterCompleteAddingOnEmptyQueue_ReturnsTrue()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            queue.CompleteAdding();
            Assert.That(queue.IsCompleted, Is.True);
        }
        public void GetEnumerator_ModDuringEnumeration_RetainsSnapshot()
        {
            var queue      = new AsyncProducerConsumerQueue <int>(new[] { 1, 2, 3 });
            var seq        = queue as IEnumerable <int>;
            var enumerator = seq.GetEnumerator();

            bool hasNext = enumerator.MoveNext();

            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(1));

            queue.Enqueue(4);
            var num = queue.Dequeue();

            Assert.That(num, Is.EqualTo(1));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(2));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(3));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.False);
        }
        public void StandardAsyncSingleConsumerCode()
        {
            Test.Async(async() =>
            {
                var queue    = new AsyncProducerConsumerQueue <int>();
                var producer = TaskShim.Run(() =>
                {
                    queue.Enqueue(3);
                    queue.Enqueue(13);
                    queue.Enqueue(17);
                    queue.CompleteAdding();
                });

                var results = new List <int>();
                while (await queue.OutputAvailableAsync())
                {
                    results.Add(queue.Dequeue());
                }

                Assert.AreEqual(results.Count, 3);
                Assert.AreEqual(results[0], 3);
                Assert.AreEqual(results[1], 13);
                Assert.AreEqual(results[2], 17);
            });
        }
        public void IsCompleted_AfterCompleteAddingOnNonEmptyQueue_ReturnsFalse()
        {
            var queue = new AsyncProducerConsumerQueue <int>(new[] { 1 });

            queue.CompleteAdding();
            Assert.That(queue.IsCompleted, Is.False);
        }
Пример #21
0
        public void EnqueueAfterComplete()
        {
            var queue = new AsyncProducerConsumerQueue <int> (2);

            queue.CompleteAdding();
            Assert.ThrowsAsync <InvalidOperationException> (() => queue.EnqueueAsync(5).AsTask(), "#1");
        }
        public void IsCompleted_AfterEnqueue_ReturnsFalse()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            queue.Enqueue(1);
            Assert.That(queue.IsCompleted, Is.False);
        }
        public async Task <List <IDownload> > Process(CancellationToken token, ILog log)
        {
            log.Debug($"{nameof(BackgroundDownloader)} started");
            var       errors = new AsyncProducerConsumerQueue <IDownload>();
            IDownload item;
            int       success;

            for (success = 0; (item = await GetItem(token)) != null;)
            {
                // TODO: add second queue, semaphore and support for retries
                try
                {
                    await filesystemTools.WriteFileWithCompletionMark(item.Location, item.DesiredName, async() => await item.GetContent(token), token, log);

                    success++;
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    item.AddError(e);
                    await errors.EnqueueAsync(item, token);

                    log.Warn($"Error downloading {item}", e);
                }
            }

            errors.CompleteAdding();
            var errorList = errors.GetConsumingEnumerable(token).ToList();

            log.Info($"All downloads completed. {success} successful, {errorList.Count} failed");
            return(errorList);
        }
Пример #24
0
        public GroupConsumer(IRouter router, string groupId, string protocolType, JoinGroupResponse response, IConsumerConfiguration configuration = null, IImmutableDictionary <string, IMembershipEncoder> encoders = null, bool?leaveRouterOpen = null, bool?autoConsume = null)
        {
            Router           = router;
            _leaveRouterOpen = leaveRouterOpen.GetValueOrDefault(true);
            AutoConsume      = autoConsume.GetValueOrDefault(false);
            Configuration    = configuration ?? ConsumerConfiguration.Default;
            Encoders         = encoders ?? ConnectionConfiguration.Defaults.Encoders();

            if (!Encoders.ContainsKey(protocolType ?? ""))
            {
                throw new ArgumentOutOfRangeException(nameof(protocolType), $"ProtocolType {protocolType} is unknown");
            }

            GroupId      = groupId;
            MemberId     = response.member_id;
            ProtocolType = protocolType;

            OnJoinGroup(response);

            // Attempt to send heartbeats at half intervals to better ensure we don't miss the session timeout deadline
            // TODO: should this be something like Math.Min(Configuration.GroupHeartbeat.TotalMilliseconds, Configuration.GroupRebalanceTimeout.TotalMilliseconds) instead?
            _heartbeatDelay   = TimeSpan.FromMilliseconds(Configuration.GroupHeartbeat.TotalMilliseconds / 2);
            _heartbeatTask    = Task.Factory.StartNew(DedicatedHeartbeatAsync, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            _stateChangeQueue = new AsyncProducerConsumerQueue <ApiKey>();
            _stateChangeTask  = Task.Factory.StartNew(DedicatedStateChangeAsync, _disposeToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
Пример #25
0
        public async Task OutputAvailableAsync_NoItemsInQueue_IsNotCompleted()
        {
            AsyncProducerConsumerQueue <int> queue = new AsyncProducerConsumerQueue <int>();

            Task <bool> task = queue.OutputAvailableAsync();

            await AsyncAssert.NeverCompletesAsync(task).ConfigureAwait(false);
        }
Пример #26
0
        public async Task DequeueAsync_Empty_DoesNotComplete()
        {
            AsyncProducerConsumerQueue <int> queue = new AsyncProducerConsumerQueue <int>();

            Task <int> task = queue.DequeueAsync();

            await AsyncAssert.NeverCompletesAsync(task).ConfigureAwait(false);
        }
        public async Task EnqueueAsync_Full_DoesNotComplete()
        {
            var queue = new AsyncProducerConsumerQueue <int>(new[] { 13 }, 1);

            var task = queue.EnqueueAsync(7);

            await AsyncAssert.NeverCompletesAsync(task);
        }
        public void CompleteAdding_MultipleTimes_DoesNotThrow()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            queue.CompleteAdding();

            queue.CompleteAdding();
        }
        public async Task OutputAvailableAsync_NoItemsInQueue_IsNotCompleted()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            var task = queue.OutputAvailableAsync();

            await AsyncAssert.NeverCompletesAsync(task);
        }
        public async Task DequeueAsync_EmptyAndComplete_ThrowsException()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            queue.CompleteAdding();

            await AsyncAssert.ThrowsAsync <InvalidOperationException>(() => queue.DequeueAsync());
        }
        public async Task DequeueAsync_Empty_DoesNotComplete()
        {
            var queue = new AsyncProducerConsumerQueue <int>();

            var task = queue.DequeueAsync();

            await AsyncAssert.NeverCompletesAsync(task);
        }
Пример #32
0
        public async Task EnqueueAsync_CompleteAdding_ThrowsException()
        {
            AsyncProducerConsumerQueue <int> queue = new AsyncProducerConsumerQueue <int>();

            queue.CompleteAdding();

            await AsyncAssert.ThrowsAsync <InvalidOperationException>(() => queue.EnqueueAsync(3)).ConfigureAwait(false);
        }
        public void EnqueueAsync_SpaceAvailable_EnqueuesItem()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();

                await queue.EnqueueAsync(3);
                var result = await queue.DequeueAsync();

                Assert.AreEqual(3, result);
            });
        }
        public void TryEnqueueAsync_SpaceAvailable_EnqueuesItem()
        {
            AsyncContext.Run(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();

                var result = await queue.TryEnqueueAsync(3);
                var dequeueResult = await queue.DequeueAsync();

                Assert.IsTrue(result);
                Assert.AreEqual(3, dequeueResult);
            });
        }
        public void ConstructorWithCollection_AddsItems()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>(new[] { 3, 5, 7 });

                var result1 = await queue.DequeueAsync();
                var result2 = await queue.DequeueAsync();
                var result3 = await queue.DequeueAsync();

                Assert.AreEqual(3, result1);
                Assert.AreEqual(5, result2);
                Assert.AreEqual(7, result3);
            });
        }
        public void EnqueueToAnyAsync_SpaceAvailable_EnqueuesItem()
        {
            AsyncContext.Run(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>(new[] { 3 }, 1);
                var queue2 = new AsyncProducerConsumerQueue<int>();
                var queues = new[] { queue1, queue2 };

                var result = await queues.EnqueueToAnyAsync(13);
                var dequeueResult = await queue2.DequeueAsync();

                Assert.AreSame(queue2, result);
                Assert.AreEqual(13, dequeueResult);
            });
        }
        public void TryEnqueueAsync_SpaceAvailable_Completes()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var task = queue.TryEnqueueAsync(7);

                await queue.DequeueAsync();
                var result = await task;

                Assert.IsTrue(result);
            });
        }
        public void EnqueueToAnyAsync_Cancelled_Throws()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queue2 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queues = new[] { queue1, queue2 };
                var cts = new CancellationTokenSource();
                var task = queues.EnqueueToAnyAsync(7, cts.Token);

                cts.Cancel();

                await AssertEx.ThrowsExceptionAsync<OperationCanceledException>(() => task);
            });
        }
        public void TryEnqueueToAnyAsync_SpaceAvailable_Completes()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queue2 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queues = new[] { queue1, queue2 };
                var task = queues.TryEnqueueToAnyAsync(7);

                await queue2.DequeueAsync();
                var result = await task;

                Assert.AreSame(queue2, result);
            });
        }
        public void TryDequeueFromAnyAsync_Empty_DoesNotComplete()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>();
                var queue2 = new AsyncProducerConsumerQueue<int>();
                var queues = new[] { queue1, queue2 };

                var task = queues.TryDequeueFromAnyAsync();

                await AssertEx.NeverCompletesAsync(task);
            });
        }
 public void IsCompleted_AfterEnqueue_ReturnsFalse()
 {
     var queue = new AsyncProducerConsumerQueue<int>();
     queue.Enqueue(1);
     Assert.That(queue.IsCompleted, Is.False);
 }
        public void EnqueueAsync_Full_DoesNotComplete()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);

                var task = queue.EnqueueAsync(7);

                await AssertEx.NeverCompletesAsync(task);
            });
        }
        public void DequeueFromAnyAsync_Empty_ItemAdded_Completes()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>();
                var queue2 = new AsyncProducerConsumerQueue<int>();
                var queues = new[] { queue1, queue2 };
                var task = queues.DequeueFromAnyAsync();

                await queue2.EnqueueAsync(13);
                var result = await task;

                Assert.IsTrue(result.Success);
                Assert.AreSame(queue2, result.Queue);
                Assert.AreEqual(13, result.Item);
            });
        }
 public void GetEnumerator_ItemsInQueue_ReturnsItems()
 {
     var queue = new AsyncProducerConsumerQueue<int>(new[] { 1, 2, 3 });
     var seq = queue as IEnumerable<int>;
     Assert.That(seq, Is.EqualTo(new[] { 1, 2, 3 }));
 }
 public void GetEnumerator_NoItemsInQueue_ReturnsEmptySeq()
 {
     var queue = new AsyncProducerConsumerQueue<int>();
     var seq = queue as IEnumerable<int>;
     Assert.That(seq.Count(), Is.EqualTo(0));
 }
        public void GetEnumerator_ModDuringEnumeration_RetainsSnapshot()
        {
            var queue = new AsyncProducerConsumerQueue<int>(new[] { 1, 2, 3 });
            var seq = queue as IEnumerable<int>;
            var enumerator = seq.GetEnumerator();

            bool hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(1));

            queue.Enqueue(4);
            var num = queue.Dequeue();
            Assert.That(num, Is.EqualTo(1));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(2));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.True);
            Assert.That(enumerator.Current, Is.EqualTo(3));

            hasNext = enumerator.MoveNext();
            Assert.That(hasNext, Is.False);
        }
        public void GetEnumerator_ItemInQueue_DoesNotConsumeItem()
        {
            var queue = new AsyncProducerConsumerQueue<int>(new[] { 1 });
            var seq = queue as IEnumerable<int>;

            // Force enumeration
            int sum = seq.Sum();
            Assert.That(sum, Is.EqualTo(1));

            int val = queue.Dequeue();
            Assert.That(val, Is.EqualTo(1));
        }
        public void StandardAsyncSingleConsumerCode()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();
                var producer = TaskShim.Run(() =>
                {
                    queue.Enqueue(3);
                    queue.Enqueue(13);
                    queue.Enqueue(17);
                    queue.CompleteAdding();
                });

                var results = new List<int>();
                while (await queue.OutputAvailableAsync())
                {
                    results.Add(queue.Dequeue());
                }

                Assert.AreEqual(results.Count, 3);
                Assert.AreEqual(results[0], 3);
                Assert.AreEqual(results[1], 13);
                Assert.AreEqual(results[2], 17);
            });
        }
 public void IsCompleted_AfterCompleteAddingOnNonEmptyQueue_ReturnsFalse()
 {
     var queue = new AsyncProducerConsumerQueue<int>(new[] { 1 });
     queue.CompleteAdding();
     Assert.That(queue.IsCompleted, Is.False);
 }
 public void IsCompleted_AfterCompleteAddingOnEmptyQueue_ReturnsTrue()
 {
     var queue = new AsyncProducerConsumerQueue<int>();
     queue.CompleteAdding();
     Assert.That(queue.IsCompleted, Is.True);
 }
        public void EnqueueAsync_SpaceAvailable_Completes()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var task = queue.EnqueueAsync(7);

                await queue.DequeueAsync();

                await task;
            });
        }
        public void OutputAvailableAsync_ItemInQueueAndCompleted_ReturnsTrue()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();
                queue.Enqueue(13);
                queue.CompleteAdding();

                var result = await queue.OutputAvailableAsync();
                Assert.IsTrue(result);
            });
        }
        public void TryEnqueueToAnyAsync_Full_DoesNotComplete()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queue2 = new AsyncProducerConsumerQueue<int>(new[] { 13 }, 1);
                var queues = new[] { queue1, queue2 };

                var task = queues.TryEnqueueToAnyAsync(7);

                await AssertEx.NeverCompletesAsync(task);
            });
        }
        public void CompleteAdding_MultipleTimes_DoesNotThrow()
        {
            var queue = new AsyncProducerConsumerQueue<int>();
            queue.CompleteAdding();

            queue.CompleteAdding();
        }
        public void DequeueAsync_Cancelled_Throws()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();
                var cts = new CancellationTokenSource();
                var task = queue.DequeueAsync(cts.Token);

                cts.Cancel();

                await AssertEx.ThrowsExceptionAsync<OperationCanceledException>(() => task);
            });
        }
        public void DequeueFromAnyAsync_MultipleHaveEntries_OnlyDequeuesOne()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>(new[] { 5 });
                var queue2 = new AsyncProducerConsumerQueue<int>(new[] { 7 });
                var queues = new[] { queue1, queue2 };

                var result = await queues.DequeueFromAnyAsync();
                await ((result.Queue == queue1) ? queue2 : queue1).DequeueAsync();
            });
        }
        public void DequeueAsync_Empty_ItemAdded_Completes()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();
                var task = queue.DequeueAsync();

                await queue.EnqueueAsync(13);
                var result = await task;

                Assert.AreEqual(13, result);
            });
        }
        public void EnqueueToAnyAsync_MultipleHaveRoom_OnlyEnqueuesOne()
        {
            Test.Async(async () =>
            {
                var queue1 = new AsyncProducerConsumerQueue<int>();
                var queue2 = new AsyncProducerConsumerQueue<int>();
                var queues = new[] { queue1, queue2 };

                var result = await queues.EnqueueToAnyAsync(13);
                Task task = ((result == queue1) ? queue2 : queue1).DequeueAsync();
                await result.DequeueAsync();

                await AssertEx.NeverCompletesAsync(task);
            });
        }
        public void IsCompleted_Initially_ReturnsFalse()
        {
            // For empty queue
            var emptyQueue = new AsyncProducerConsumerQueue<int>();
            Assert.That(emptyQueue.IsCompleted, Is.False);

            // For non-empty queue
            var nonEmptyQueue = new AsyncProducerConsumerQueue<int>(new[] { 1, 2, 3 });
            Assert.That(nonEmptyQueue.IsCompleted, Is.False);
        }
        public void TryDequeueAsync_Empty_DoesNotComplete()
        {
            Test.Async(async () =>
            {
                var queue = new AsyncProducerConsumerQueue<int>();

                var task = queue.TryDequeueAsync();

                await AssertEx.NeverCompletesAsync(task);
            });
        }