public void ShouldWaitForEnqueue()
        {
            var buffer         = new InMemoryBuffer();
            var stop           = false;
            var attemptsToRead = 0;

            var thread = new Thread(() =>
            {
                while (!stop)
                {
                    var message = buffer.WaitOneAndPeek(CancellationToken.None);
                    Thread.Sleep(1);
                    attemptsToRead++;
                    if (message != null)
                    {
                        buffer.Dequeue(CancellationToken.None);
                    }
                }
            });

            thread.Start();

            for (int i = 0; i < 10; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    buffer.Enqueue(new RawMessage(new byte[0], string.Empty), CancellationToken.None);
                    buffer.Enqueue(new RawMessage(new byte[0], string.Empty), CancellationToken.None);
                });
            }

            Thread.Sleep(25);
            stop = true;
            Assert.AreEqual(20, attemptsToRead);
        }
Esempio n. 2
0
        public async Task ShouldWaitForEnqueue()
        {
            var buffer         = new InMemoryBuffer();
            var cts            = new CancellationTokenSource();
            var attemptsToRead = 0;

            var thread = new Thread(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    try
                    {
                        var message = buffer.WaitOneAndPeek(cts.Token);
                        Thread.Sleep(50);
                        attemptsToRead++;
                        if (message != null)
                        {
                            buffer.Dequeue(cts.Token);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        //that's ok )
                    }
                }
            });

            thread.Start();

            var writeTasks = Enumerable.Range(0, 10).Select(i =>
                                                            Task.Factory.StartNew(() =>
            {
                buffer.Enqueue(new RawMessage(new byte[0], string.Empty), cts.Token);
                buffer.Enqueue(new RawMessage(new byte[0], string.Empty), cts.Token);
            })
                                                            );

            await Task.WhenAll(writeTasks);

            await Task.Delay(TimeSpan.FromSeconds(2));

            cts.Cancel();

            Assert.AreEqual(20, attemptsToRead);
        }
 public void Dequeue(CancellationToken cancellationToken)
 {
     _buffer.Dequeue(cancellationToken);
 }